2017-01-31 10 views
1

関数のcheckSuggestionListの値をthis.state.validSearchParentInputに戻す必要があります。関数checkSuggestionListは適切な値を返しますが、this.state.validSearchParentInputには渡されません。私はsetStateが関数checkSuggestionListが終了する前に値を設定すると信じています。React - setStateへの関数の戻り値

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() 
    } 

答えて

3

setStateは、リアクトコンポーネントis not guaranteed to be synchronousの機能ですが、パフォーマンス上の理由から非同期に実行される可能性があります。

変更が適用される前の状態を読み取っている可能性があります。

ことは、これを解決するには、状態遷移が行われた後に実行されるコールバック関数をとるsetStateの二番目のパラメータを、利用することができる:

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

setStateアクションは非同期です。これはsetStateのドキュメントで説明されています(参照:https://facebook.github.io/react/docs/react-component.html#setstate

setState()はthis.stateをただちに変更するのではなく、保留状態遷移を作成します。このメソッドを呼び出した後this.stateにアクセスすると、潜在的に既存の値が返される可能性があります。 setStateへの呼び出しの同期動作を保証するものではなく、性能向上のために呼び出しをバッチ処理することもできます。