反应.如何用以前的状态更新状态?

Max*_*fen 4 javascript reactjs

我正在尝试更新状态,基于之前的状态(array of objects),新的传入值为fase object.但由于某些原因,它不会发生......

我做错了什么?我的代码:

   handleCommentSubmit = (newEmployer) => {
       console.log('handleCommentSubmit BEFORE', this.state.employers, newEmployer); // array(5)
       this.setState((prevState, newEmployer) => { 
         employers: prevState.employers + newEmployer
       });
       console.log('handleCommentSubmit AFTER', this.state.employers); // still array(5)
   }
Run Code Online (Sandbox Code Playgroud)

我的日志:

handleCommentSubmit BEFORE (6) [{…}, {…}, {…}, {…}, {…}, {…}], newEmployer: {first_name: "sdfsdf", last_name: "sdfsdf", birth_date: "123123-03-12", salary: "123123123"}
handleCommentSubmit AFTER (6) [{…}, {…}, {…}, {…}, {…}, {…}]
Run Code Online (Sandbox Code Playgroud)

May*_*kla 6

变化:

1- setState是异步,因此使用回调来检查更新的值.

2-用于[].concat在数组中推送新值,+将无法正常工作.

3-您没有object从更新程序功能返回.

写这样:

handleCommentSubmit = (newEmployer) => {
    this.setState((prevState, newEmployer) => ({
        employers: prevState.employers.concat(newEmployer)
    }), () => {
        console.log('handleCommentSubmit AFTER', this.state.employers);
    }); 
}
Run Code Online (Sandbox Code Playgroud)

查看此答案以获取更多详细信息

为什么调用setState方法不会立即改变状态?


asi*_*niy -7

this.setState应该接收对象作为参数。不是一个函数。您可以轻松使用this.state

handleCommentSubmit = (newEmployer) => {
  this.setState({ 
    employers: this.state.employers.concat(newEmployer)
  });
}
Run Code Online (Sandbox Code Playgroud)

  • -1。`this.setState` *确实*接受函数作为参数,请参阅[文档](https://reactjs.org/docs/react-component.html#setstate)。 (2认同)