2017-01-25 22 views
2

私の状態からフェッチ呼び出し(検索語など)にデータを渡したいとします。状態が変わると、データを再フェッチする必要があります。React Redux状態と状態の変更を使用してデータを再フェッチする

ライフサイクルメソッドはこれを行う場所のようですが、私がそれらを使用すると、何もしません(レンダリングは状態変更前に呼び出されます)、または無限ループになります。

@connect((store) => { 
 
    return { 
 
     collections : store.collections.collections 
 
    } 
 
}, { 
 
    fetchCollections 
 
}) 
 
export default class CollectionPane extends Component { 
 

 
    constructor(props){ 
 
     super(props); 
 

 
     this.state = { 
 
      term : null 
 
     } 
 
    } 
 

 
    componentWillMount(){ 
 
     this.handleFetchCollections(this.state.term); // This loads initial ok 
 
    } 
 

 
    componentDidUpdate(){ 
 
     // this.handleFetchCollections(this.state.term); // This causes loop 
 
    } 
 

 
    handleFetchCollections(props, sort){ 
 
     log('Fetching...', 'green'); 
 
     this.props.fetchCollections(props, sort); 
 
    } 
 

 
    onSearch(){ 
 
\t \t 
 
\t \t const term = "test example"; 
 
\t \t 
 
\t \t this.setState({ 
 
\t \t \t term 
 
\t \t }) 
 
    } 
 

 
    render(){ 
 
     const { collections } = this.props; 
 

 
     return (
 
      <div> 
 
       <a style={{ display: "block", padding: "1em" }} onClick={this.onSearch.bind(this)}>Search</a> 
 

 
       <CollectionList collections={collections} /> 
 
      </div> 
 
     ); 
 
    } 
 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react-dom.min.js"></script>

答えて

2

あなたがフェッチ実行する前に、以前の状態と新しい状態を比較する必要があります:

componentDidUpdate(prevProps, prevState) { 
    if (prevState.term !== this.state.term) { 
     this.handleFetchCollections(this.state.term); 
    } 
} 
+0

Worked perfect。ありがとう! –

1

あなたがすべき反応-再来とここ

は私の簡素化コードがあります行動や減量者によってあなたの国家を変えてください。次に、ここで説明する非同期アクションを使用できます。http://redux.js.org/docs/advanced/AsyncActions.html

+0

あなたが意味するものの例があれば興味があります –

関連する問題