如何在文本输入中调用异步函数?

How to call an async function in textinput?

如何在 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>
    );
}

有错误"await is a reserved words",有知道的吗?

无需await关键字即可调用函数

this.getTxt()

您的代码会像:

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 }}
            >{ this.getTxt() }
            </TextInput>
            <Button onPress = { this.FunctionToOpenFirstActivity } title = 'Save'/>
        </View>
    );
}

Render 不是一个异步函数,所以你不能在 render 中使用 await,你可以在 componentWillMount 中使用它并保持它在 render 方法中的状态

您需要重新排列代码以获得所需的结果。您不能在 render() 中使用 await ,它不是异步函数。如果你在没有等待的情况下调用异步函数 getTxt,它将 return 一个承诺。因此文件文本在渲染时将为空。您需要利用状态在值更改时自动重新渲染。

// 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>
    );
}