React - Return 函数值到 setState

React - Return function value to setState

我需要 return 函数的 checkSuggestionList 值到 this.state.validSearchParentInput 。函数 checkSuggestionList return 是正确的值,但它没有传递给 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()
  }

setState 操作是异步的。这在 setState 的文档中有解释。(供参考:https://facebook.github.io/react/docs/react-component.html#setstate

setState() 不会立即改变 this.state 而是创建一个挂起的状态转换。调用此方法后访问 this.state 可能会 return 现有值。无法保证对 setState 的调用同步操作,并且可以对调用进行批处理以提高性能。

React 组件 is not guaranteed to be synchronoussetState 功能,但出于性能原因可能会异步执行。

您可能正在阅读更改应用前的状态。

要解决此问题,您可以利用 setState 的第二个参数,它采用在状态转换完成后执行的回调函数:

this.setState({
  validSearchParentInput: this.checkSuggestionList(newValue),
  searchParentsValue: newValue
}, function() {
    this.checkProgress()
})