【发布时间】:2017-10-11 03:21:48
【问题描述】:
我正在阅读有关 React setState 的文档,其中说:
setState() 不会立即改变 this.state 而是创建一个挂起的状态转换。调用此方法后访问 this.state 可能会返回现有值。
现在我有一个这样的组件:
class NoteScreenComponent extends React.Component {
constructor() {
super();
this.state = { note: Note.newNote() }
}
componentWillMount() {
this.setState({ note: this.props.note });
}
noteComponent_change = (propName, propValue) => {
this.setState((prevState, props) => {
let note = Object.assign({}, prevState.note);
note[propName] = propValue;
return { note: note }
});
}
title_changeText = (text) => {
this.noteComponent_change('title', text);
}
body_changeText = (text) => {
this.noteComponent_change('body', text);
}
saveNoteButton_press = () => {
// Save note to SQL database
Note.save(this.state.note)
}
render() {
return (
<View>
<TextInput value={this.state.note.title} onChangeText={this.title_changeText} />
<TextInput value={this.state.note.body} onChangeText={this.body_changeText} />
<Button title="Save note" onPress={this.saveNoteButton_press} />
</View>
);
}
}
我想知道的是,由于setState 不会立即更新state,我怎么知道我保存在saveNoteButton_press 中的注释是否是状态的当前版本?是否有一些回调或我可以轮询以了解 state 是否已完全更新?
【问题讨论】:
-
render()作为告诉你状态更新完成的回调怎么样?我们知道它已经准备好了,对吧?
标签: reactjs asynchronous ecmascript-6 state