ReactJS setState 仅在嵌套在 setState 中时才有效

Rec*_*cur 5 javascript ecmascript-6 reactjs

问题:当我使用 this.setState 并在回调中输出状态时,它根本不会改变,但是当我将 setstate 嵌套在 setstate 中时,它将正常工作。

示例:这不起作用 -

this.setState({
    data: newData
});
Run Code Online (Sandbox Code Playgroud)

这确实有效 -

this.setState({
    data: newData
}, () => {
    this.setState({
        data: newData
    });
});
Run Code Online (Sandbox Code Playgroud)

这与反应批量状态更新的方式有关吗?

这是实际的代码,其中 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
    });
  });
}
Run Code Online (Sandbox Code Playgroud)

这是与 cancelCPIndexChanges 同一级别的另一个函数,可以修改 coursePages 的状态:

showEditingCoursePage(index){
  let temp = this.state.coursePages;
  temp[index].editingCoursePage = true;
  this.setState({
    coursePages: temp
  });    
}
Run Code Online (Sandbox Code Playgroud)

这些函数位于 course.js 中。这两个函数都会传递到 CoursePages.js,然后传递到 CoursePage.js。

Mat*_*and 3

根据: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您仍然拥有对该值的引用,因此可以直接使用它。