【问题标题】:setState delay in reactsetState 延迟反应
【发布时间】:2019-08-27 21:44:10
【问题描述】:

我目前在 react native 中有一个函数,它执行以下操作:

resetThenSet = (id, arrayId, title) => {
    if(arrayId != 'selectProduct') {
            // Setting state for each selected dropdown in selectedDropdowns
             this.setState({
               dataShowingToggle: true,
               selectedDropdowns: {...this.state.selectedDropdowns, [arrayId]: title}
             }, this.getProductCost(arrayId, id)
           );
}

我运行上面的程序,我可以确认 arrayId 和 title 变量是有效的并且包含数据。 arrayId 也不是“selectProduct”。我在调试时在其中添加了一个 console.log 以确保它运行,确实如此。我期望的预期行为是状态会立即更新。

但是 selectedDropdowns 的状态没有更新。当我添加: console.log(this.state) this.setState 更新后没有变化。如果我运行该函数两次,它将在第二次运行时更新。

为了进一步测试,我添加了如下静态输入:

this.setState({
           dataShowingToggle: true,
           selectedDropdowns: {...this.state.selectedDropdowns, testField: 'me here'}
         }, this.getProductCost(arrayId, id)
       );
       console.log(this.state);

它只在第一次运行后更新状态。我错过了什么吗?

更新: 我更新了代码以在回调 setstate 时运行 console.log:

  if(arrayId != 'selectProduct') {
    // Setting state for each selected dropdown in selectedDropdowns
    console.log(arrayId + title);
    console.log('i run');
     this.setState({
       dataShowingToggle: true,
       selectedDropdowns: {...this.state.selectedDropdowns, [arrayId]: title}
     }, console.log(this.state)
   );
  };

console.log 是 arrayId + 标题的“quantityProduct 25” console.log(我运行) 然后这个状态不显示quantityProduct 25

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

setState 是异步的。这就是函数调用具有可选回调的原因。

我认为您可能还有其他问题。

尝试在您调用 setState 时将该控制台日志放入回调函数中,以查看状态何时更新为您提供的值。

【讨论】:

  • 我更新了 console.log 现在作为回调函数,它仍然没有显示更新状态。 @亚伦
  • @FabricioG 不,你没有,回调需要评估为函数,你的回调是你的 console.log 的返回值。
  • 啊我很抱歉修复@Aaron
  • @FabricioG 我不是 Aaron,我不知道他是否需要修复 :)
  • 大声笑,我今天到处都搞砸了! @DaveNewton
猜你喜欢
  • 2023-01-11
  • 2019-06-07
  • 2020-11-20
  • 2016-01-10
  • 2021-11-06
  • 2020-05-05
  • 1970-01-01
  • 2013-11-09
  • 1970-01-01
相关资源
最近更新 更多