我正在尝试根据以前的状态(array of objects)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)
   }

我的日志:
handleCommentSubmit BEFORE (6) [{…}, {…}, {…}, {…}, {…}, {…}], newEmployer: {first_name: "sdfsdf", last_name: "sdfsdf", birth_date: "123123-03-12", salary: "123123123"}
handleCommentSubmit AFTER (6) [{…}, {…}, {…}, {…}, {…}, {…}]

最佳答案

this.setState应该接收object作为参数。不是功能。
您可以轻松地使用this.state:

handleCommentSubmit = (newEmployer) => {
  this.setState({
    employers: this.state.employers.concat(newEmployer)
  });
}

关于javascript - react 。如何用以前的状态更新状态?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49792757/

10-09 07:01