问题: 当我使用this.setState并且我在回调中输出状态时,它根本没有改变,但是当我将setstate嵌套在setstate中时它将正常工作。
实施例: 这不起作用 -
this.setState({
data: newData
});
这确实有效 -
this.setState({
data: newData
}, () => {
this.setState({
data: newData
});
});
这是否与反应批量状态更新的方式有关?
这是setstate不起作用的实际代码,除非我嵌套它(我已经尝试在此函数中注释掉所有内容并使用setState将coursePage设置为null但它没有&t; t工作,除非它嵌套):
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。
答案 0 :(得分: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.
(我过去自己也注意到了这一点)
我不是100%肯定,但我猜你的回调函数中的第二个setState
是在创建第二个之前“刷新”挂起状态转换。
我不清楚你想要消耗新的状态值?它应该在render
方法中,您可以确定它已被更新(当状态转换触发渲染时)。如果您想在setState
之后立即使用它,您仍然可以使用该值,那么可以直接使用它。
答案 1 :(得分:1)
因为所述setState异步行为。有两种方法可以在渲染之前访问新更新的状态值
使用setState方法的回调函数
使用componentDidUpdate方法。使用nextState参数可以访问最新状态。但请确保您应该在