如何在textinput中调用异步函数?

getTxt = async () => {

    filetxt = 'abc';
    currentFileName = this.props.navigation.getParam("currentFileName");
    console.log(currentFileName);

    try {

        filetxt = FileSystem.readAsStringAsync(`${FileSystem.documentDirectory}${currentFileName}.txt`, { encoding: FileSystem.EncodingTypes.UTF8 });

        console.log(filetxt);

    } catch (error) {
        console.log(error);
    }

    return filetxt;
}

render() {

    return (
        <View style={{ flex: 1 }}>
            <TextInput
                multiline = {true}
                style={{ margin : 10 }}
            >{ await this.getTxt() }
            </TextInput>
            <Button onPress = { this.FunctionToOpenFirstActivity } title = 'Save'/>
        </View>
    );
}


有一个错误“等待是保留字”,知道吗?

最佳答案

您需要重新排列代码以获得所需的结果。您不能在不是异步函数的render()中使用await。如果不等待就调用异步函数getTxt,它将返回一个Promise。因此,文件文本在呈现时将为空。您需要利用状态在值更改时自动重新呈现。

// Initialise filetext with state
constructor(props) {
    super(props);
    this.state = {
      filetext: ""
    };
  }
// Make componentWillMount async and invoke getTxt with await
async componentWillMount() {
 let text = await this.getTxt();
 this.setState({ filetext: text });
}

//Access filetext from the state so that it will automatically re-render when value changes

render() {

    return (
        <View style={{ flex: 1 }}>
            <TextInput
                multiline = {true}
                style={{ margin : 10 }}
            >{ this.state.filetext }
            </TextInput>
            <Button onPress = { this.FunctionToOpenFirstActivity } title = 'Save'/>
        </View>
    );
}

10-06 12:02