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

时间:2019-02-15 05:52:30

标签: javascript reactjs react-native async-await react-lifecycle-hooks

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

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

3 个答案:

答案 0 :(得分:2)

您需要重新排列代码以获得所需的结果。您不能在不是异步函数的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>
    );
}

答案 1 :(得分:0)

您可以在不使用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>
    );
}

答案 2 :(得分:0)

Render不是异步函数,因此您不能在render中使用await,可以在componentWillMount中进行操作,并将其保持在将状态置于render方法中的状态