【问题标题】:How can I do ajax call each time when store gets updated?每次更新商店时如何进行ajax调用?
【发布时间】:2017-08-16 19:20:58
【问题描述】:

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

提前致谢。

【问题讨论】:

标签: reactjs redux redux-thunk


【解决方案1】:

你可以使用 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 将在每次调度时被调用,因此请注意不要创建无限循环。这也是为什么在执行回调函数时必须手动检查更改的原因。

【讨论】:

    猜你喜欢
    • 2013-05-30
    • 1970-01-01
    • 1970-01-01
    • 2018-06-29
    • 2021-09-05
    • 1970-01-01
    • 1970-01-01
    • 2016-02-06
    • 2021-10-16
    相关资源
    最近更新 更多