如何在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()中使用它不是异步函数。如果您无需等待调用异步函数getTXT,它将返回承诺。因此,FileText在渲染时将是空的。您需要利用状态在值更改时自动重新渲染。
// 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>
);
}
您可以在没有等待关键字的情况下调用该函数
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>
);
}
渲染不是异步函数,因此您无法在渲染中使用等待,您可以在componentwillmount中进行操作,并将其保持在一个状态下,将其保持在渲染方法中的状态