每次商店更新时如何进行ajax调用?

时间:2017-08-16 19:20:58

标签: reactjs redux redux-thunk

每次商店更新时如何进行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);
&#13;
&#13;
&#13;

提前致谢。

1 个答案:

答案 0 :(得分: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,所以注意不要创建无限循环。这也是您在执行回调函数时必须手动检查更改的原因。