【问题标题】:React. How to update the state with previous state?做出反应。如何用以前的状态更新状态?
【发布时间】:2018-04-12 09:21:32
【问题描述】:

我正在尝试根据先前的状态 (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) [{…}, {…}, {…}, {…}, {…}, {…}]

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

变化:

1- setState 是异步的,所以使用回调来检查更新的值。

2- 使用[].concat 向数组中推送新值,+ 将不起作用。

3- 您没有从更新程序函数返回 object。

这样写:

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

查看此答案了解更多详情:

Why calling setState method doesn't mutate the state immediately?

【讨论】:

  • 查看 React 的页面:reactjs.org/docs/… 以进一步增强 @Mayank 解决方案的相关性。
【解决方案2】:

如果您的 employers 是一个数组,您可以在 setState 中使用 spread operator:

[...prevState.employers, newEmployer]

但你根本不需要prevState。你可以:

this.setState({ 
         employers: [...this.state.employers, newEmployer]
       });

【讨论】:

    【解决方案3】:

    如果您调用 setState,它不会在下一行立即更新。它将在调用渲染方法后更新。 如果你想看到updatedState,你可以像这样在setState中写一个回调函数。

    this.setState((prevState, newEmployer) => { 
             employers: prevState.employers + newEmployer
           }, () => console.log('UpdatedState', this.state.employers));
    

    【讨论】:

      【解决方案4】:

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

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

      【讨论】:

      • -1。 this.setState确实接受函数作为参数,请参阅docs。
      • 设置状态可能是异步的,这种解决方案在某些情况下可能会导致问题。在下面查看我的解决方案。
      • 这个答案是错误的。当新状态依赖于前一个状态时,建议使用函数参数更新状态——考虑到setState 的异步性质。
      猜你喜欢
      • 1970-01-01
      • 2020-09-12
      • 1970-01-01
      • 2021-11-09
      • 2020-10-28
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      相关资源
      最近更新 更多