【问题标题】:React - Return function value to setStateReact - 将函数值返回给 setState
【发布时间】:2017-01-31 19:05:00
【问题描述】:

我需要将函数的 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()
  }

【问题讨论】:

    标签: javascript reactjs state


    【解决方案1】:

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

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

    要解决这个问题,您可以利用setState 的第二个参数,它接受一个在状态转换后执行的回调函数:

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-05-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-30
        • 2011-09-04
        相关资源
        最近更新 更多