2017-08-16 1 views
0

ストアが更新されるたびに、どのようにajaxコールを行うことができますか?ストアが更新されるたびにajax呼び出しを行う方法はありますか?

基本的に、新しいAPIパラメータで商品を取得したいとします。ページあたりのアイテムのドロップダウンがあるとします。読み込み中、つまりメソッド呼び出し時に正常に動作していますcomponentWillMount

しかし、ストアが変更されたときに再度フェッチする方法がわかりません。事前に

import React, { Component } from 'react'; 
 
import ProductsList from '../components/ProductsList' 
 
import { connect } from 'react-redux' 
 
// Action Creators 
 
import doFetchProducts from '../actions/doFetchProducts' 
 
import queryString from 'query-string' 
 

 
class Products extends Component { 
 

 
    constructor (props) { 
 
    super(props); 
 
    } 
 

 
    componentWillMount() { 
 
    this.fetch() 
 
    } 
 

 
    fetch() { 
 

 
    let q = queryString.stringify({ 
 
     categories: 'rings', 
 
     'attributes.Style': 'Classic', 
 
     limit: this.props.applyItemsPerPage, 
 
     page: 1, 
 
     status: 'Active' 
 
    }) 
 

 
    this.props.dispatch(
 
     doFetchProducts(q) 
 
    ) 
 
    } 
 

 
    render() { 
 

 
    return (
 
     <section className="content"> 
 
     <ProductsList {...this.props} /> 
 
     </section> 
 
    ); 
 
    } 
 

 
} 
 
const mapStateToProps = state => { 
 
    return { 
 
    products: state.applyFetchProducts.products, 
 
    isLoading: state.applyFetchProducts.isLoading, 
 
    itemsPerPage: state.applyItemsPerPage 
 
    } 
 
} 
 

 
export default connect(
 
    mapStateToProps 
 
)(Products);

感謝。

+1

コンポーネントが更新されたときにajaxコールを実行することを意味しますか?そのためには 'componentWillRecieveProps'を使うことができます。 https://facebook.github.io/react/docs/react-component.html#componentwillreceivepropsをご覧ください。 –

答えて

0

Reduxのstore.subscribeを使用して、変更をリスンすることができます。

componentWillMount() { 
    this.unsubscribeStore = store.subscribe(this.onStoreChange); 

    this.setState({ 
    currentState: store.getState() 
    }); 
} 

componentWillUnmount() { 
    this.unsubscribeStore(); 
} 

onStoreChange =() => { 
    const newState = store.getState(); 

    // Check the relevant part of store for changes. 
    // Depends on your store implementation 
    if (newState.reducer.prop !== this.state.currentState.reducer.prop) { 
    this.fetch(); 
    } 
} 

this.onStoreChangeは、各派遣に呼び出され、その無限ループを作成しないように注意してしまいます。これは、コールバック関数が実行されたときに手動で変更をチェックする必要がある理由もあります。

0

ストアが変更されるたびにAJAX呼び出しを行う場合は、ライフサイクルフックcomponentWillReceivePropsを使用します。そのhere.

これのドキュメント:

  • 実行されるたびに店の変化、それはしたがって、再レンダリングする新しい小道具
  • を受信して​​いる知っているコンポーネントをトリガするため。
関連する問題