我有一个带有一些状态值的 react 组件。这些值之一是compareKey。我有一个 handleChange() 函数,如果找到匹配项,它应该更新此状态。由于某些我无法弄清楚的原因,compareKey 的状态没有更新。
两个 console.log 都应该打印出“Limits”,但只有临时值打印出“Limits”。我的状态没有更新有什么原因吗?
输入代码:
<input type="text" name="keyToFind" placeholder="search here" value={this.state.keyToFind} onChange={this.handleChange.bind(this)} />
{renderOutFile}
处理更改代码:
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
});
}
控制台打印...
match found
Temp: Limits
Compare Key:
我希望比较键也能打印“限制”,但它是空白的。不知道为什么我的状态没有更新......
最佳答案
setState()
是异步的,在调用时不会更新状态。相反,它会将稍后发生的状态更改排队。 setState()
调用可以批量处理以提高效率。
https://reactjs.org/docs/react-component.html#setstate
Think of setState() as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately.
没有办法强制 React 立即更新状态。相反,您可以为 setState()
提供一个回调函数,该函数将在状态更新后立即发生。
this.setState({
compareKey: temp
}, () => {
// This function will run after state.compareKey has been set to temp
});
关于javascript - 为什么我的状态没有在找到匹配时更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47801941/