简体   繁体   English

为什么没有找到我的比赛状态更新?

[英]Why is my state not being updated on match found?

I have a react component with a few state values. 我有一个带有一些状态值的React组件。 One of these values is compareKey. 这些值之一是compareKey。 I have a handleChange() function that is suppose to update this state if it finds a match. 我有一个handleChange()函数,假设发现匹配项,该函数将更新此状态。 For someone reason I can't figure out, the state of compareKey is not updating. 由于某些原因,我无法弄清楚,compareKey的状态未更新。

The two console.logs should both print out 'Limits', but only the temp value is printing out 'Limits'. 这两个console.logs应该都打印出“ Limits”,但是只有temp值才打印出“ Limits”。 Any reason to why my state is not updating? 为什么我的状态没有更新?

Input code: 输入代码:

<input type="text" name="keyToFind" placeholder="search here" value={this.state.keyToFind} onChange={this.handleChange.bind(this)} />
{renderOutFile}

HandleChange Code: HandleChange代码:

handeChange(e) {
let target = e.target;
let value = target.type === 'checkbox' ? target.checked : target.value;
let name = target.name;
let keys = this.state.keyWordData;
let temp = '';

keys = keys.filter(obj => {
   return target.value === obj.name;
  }).map((obj,idx) => {
    console.log("match found");
    temp = obj.directs;
    this.setState({
      compareKey: temp
    });
   console.log("Temp: " + temp);
   console.log("Compare Key: " + this.state.compareKey);
  });

 this.setState({
   [name]: value
  });
}

The console prints... 控制台将打印...

match found
Temp: Limits
Compare Key: 

I would expect Compare Key to print 'Limits' as well, but it's blank. 我希望Compare Key也会打印“ Limits”,但是它是空白的。 Not sure why my state is not being updated.... 不知道为什么我的状态没有被更新...。

setState() is asynchronous and does not update the state at the moment it is called. setState()是异步的,在被调用时不会更新状态。 Instead it queues up a state change which happens later. 而是将状态更改排队,该状态更改稍后发生。 setState() calls may be batched together for efficiency. 可以将setState()调用批处理在一起以提高效率。

https://reactjs.org/docs/react-component.html#setstate https://reactjs.org/docs/react-component.html#setstate

Think of setState() as a request rather than an immediate command to update the component. 将setState()视为请求而不是立即更新组件的命令。 For better perceived performance, React may delay it, and then update several components in a single pass. 为了获得更好的感知性能,React可能会延迟它,然后在一次通过中更新几个组件。 React does not guarantee that the state changes are applied immediately. React不保证状态更改会立即应用。

There is no way to force React to update the state immediately. 无法强制React立即更新状态。 Instead, you can give setState() a callback function which will happen immediately after the state has been updated. 相反,您可以给setState()一个回调函数,该回调函数将在状态更新后立即发生。

this.setState({
  compareKey: temp
}, () => {
  // This function will run after state.compareKey has been set to temp
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM