问题:当我使用this.setState并且我在回调中输出状态时,它根本不会改变,但是当我将setstate嵌套在setstate中时它将正常工作 .
示例:这不起作用 -
this.setState({
data: newData
});
这确实有效 -
this.setState({
data: newData
}, () => {
this.setState({
data: newData
});
});
这是否与反应批次状态更新的方式有关?
这是setstate不起作用的实际代码,除非我嵌套它(我已尝试在此函数中注释掉所有内容并使用setState将coursePage设置为null但除非它是嵌套的,否则它不起作用):
cancelCPIndexChange(index){
let temp = this.state.coursePages;
this.hideEditingCoursePage(index);
let canceledIndex = temp[index];
temp = temp.slice(0, index).concat(temp.slice(index+1));
temp = temp.slice(0, parseInt(canceledIndex.course_pageindex)-1).concat(canceledIndex).concat(temp.slice(parseInt(canceledIndex.course_pageindex)-1));
this.setState({
coursePages: temp
}, () => {this.setState({
coursePages: temp
});
});
}
这是与cancelCPIndexChanges相同级别的另一个函数,它能够修改coursePages的状态:
showEditingCoursePage(index){
let temp = this.state.coursePages;
temp[index].editingCoursePage = true;
this.setState({
coursePages: temp
});
}
这些函数在course.js中 . 这两个函数都传递给CoursePages.js然后传递给CoursePage.js .
2 回答
根据:https://facebook.github.io/react/docs/component-api.html
setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.
(我过去自己也注意到了这一点)
我猜测你的回调函数中的第二个
setState
是在创建第二个之前的挂起状态转换"flushing" .我不清楚你想要消耗新的状态值?它应该在
render
方法中,您可以确定它已被更新(当状态转换触发渲染时) . 如果你想在setState
之后立即使用它,你仍然可以引用该值,那么可以直接使用它 .因为所述setState异步行为 . 有两种方法可以在渲染之前访问新更新的状态值
使用setState方法的回调函数
使用componentDidUpdate方法 . 使用nextState参数可以访问最新状态 . 但请确保您应该在其中使用setState方法