Javascript React-将函数值返回到setState
我需要将函数的Javascript React-将函数值返回到setState,javascript,reactjs,state,Javascript,Reactjs,State,我需要将函数的checkSuggestionList值返回到this.state.validSearchParentInput。函数checkSuggestionList返回正确的值,但不会传递给this.state.validSearchParentInput。我相信setState会在函数checkSuggestionList完成之前设置该值 checkSuggestionList = (newValue) => { for (let i = 0; i < nod
checkSuggestionList
值返回到this.state.validSearchParentInput
。函数checkSuggestionList
返回正确的值,但不会传递给this.state.validSearchParentInput
。我相信setState会在函数checkSuggestionList
完成之前设置该值
checkSuggestionList = (newValue) => {
for (let i = 0; i < nodes.length; i++ ) {
let node = nodes[i].name
console.log('node: ' , node)
if (node.toLowerCase() === newValue.toLowerCase()) {
console.log('did find case')
return true
} else {
console.log('didn\'t find case')
}
return false
}
}
searchParents__onChange = (event, { newValue, method }) => {
this.setState({
validSearchParentInput: this.checkSuggestionList(newValue),
searchParentsValue: newValue
})
this.checkProgress()
}
checkSuggestionList=(newValue)=>{
for(设i=0;i{
这是我的国家({
validSearchParentInput:this.checkSuggestionList(newValue),
searchParentsValue:newValue
})
这是checkProgress()
}
设置状态操作是异步的。这在setState的文档中进行了解释。(参考:)
setState()不会立即改变this.state,但会创建挂起的状态转换。调用此方法后访问this.state可能会返回现有值。无法保证对setState的调用的同步操作,调用可能会成批进行以提高性能。React组件的
setState
功能,但出于性能原因,可能会异步执行
您可能正在读取应用更改之前的状态
要解决此问题,您可以利用setState
的第二个参数,该参数接受在进行状态转换后执行的回调函数:
this.setState({
validSearchParentInput: this.checkSuggestionList(newValue),
searchParentsValue: newValue
}, function() {
this.checkProgress()
})