如何在 Redux 中为每个实例创建一个商店?

IT技术 reactjs redux react-redux
2021-05-21 21:37:09

有时,在 Redux 应用程序中为每个实例创建一个存储会很有用。Redux 的创建者自己创建了一个 Gist,描述了如何实现这一点:https : //gist.github.com/gaearon/eeee2f619620ab7b55673a4ee2bf8400

我已经在 Gist 中问过这个问题,但我认为 StackOverflow 更适合解决这个问题:

我想知道如何对dispatch组件自己的特殊存储进行操作?有没有办法访问每个(及其子组件)store-prop <Provider /><SubApp />

例如:我有一些 API 类dispatch在从远程服务器获取数据后调用但是由于我无法导入“普通”存储,处理自定义存储以使它们可用于其他类/文件/服务的最佳方法是什么?

更新 1

所以我让它工作了,但我认为这是一种非常肮脏的方式(注意UGLY?代码中注释):

供应商:

通过在构造函数中创建商店来为每个实例创建一个商店:

export default class OffersGridProvider extends React.Component {
  constructor(props) {
    super(props)
    this.store = createStore(reducers);
  }

  render() {
    return (
      <Provider store={this.store}>
        <OffersGridContainer offers={this.props.offers} />
      </Provider>
    );
  }
}

容器:

Providerdispatch这个store注入了一个方法给 my OffersGridContainer,我可以用它来将动作分派到这个实例的 store:

class OffersGridContainer extends React.Component {    
  componentDidMount() {

    // UGLY???
    const { dispatch } = this.props;

    let destinationIds = [];
    this.props.offers.forEach((offer) => {
      offer.to.forEach((destination) => {
        destinationIds.push(destination.destination);
      });
    });

    // MORE UGLY???
    destinationsApi.getDestinations(dispatch, destinationIds);
  }

  render() {
    return (
      <OffersGridLayout destinations={this.props.destinations} />
    );
  }
}

const mapStateToProps = function(store) {
  return {
    destinations: store.offersGridState.destinations
  };
}

export default connect(mapStateToProps)(OffersGridContainer);

API方法:

只需使用dispatch我作为参数传递给我的 API 方法-method:

export function getDestinations(dispatch, ids) {
  const url = $('meta[name="site-url"]').attr('content');

  const filter = ids.map((id) => {
    return `filter[post__in][]=${id}`;
  }).join('&');

  return axios.get(`${url}/wp-json/wp/v2/destinations?filter[posts_per_page]=-1&${filter}`)
    .then(response => {
      dispatch(getOffersGridSuccess(response.data));
      return response;
    });
}

更新 2

刚刚mapDispatchToProps在评论中收到了一个提示,所以我Container现在看起来像这样:

class OffersGridContainer extends React.Component {    
  componentDidMount() {
    let destinationIds = [];

    this.props.offers.forEach((offer) => {
      offer.to.forEach((destination) => {
        destinationIds.push(destination.destination);
      });
    });

    this.props.getDestinations(destinationIds);
  }

  render() {
    return (
      <OffersGridLayout destinations={this.props.destinations} />
    );
  }
}

const mapStateToProps = function(store) {
  return {
    destinations: store.offersGridState.destinations
  };
}

const mapDispatchToProps = function(dispatch) {
  return {
    getDestinations: function(ids) {
      return destinationsApi.getDestinations(dispatch, ids);
    }
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(OffersGridContainer);

更新3(最终答案)

现在一切正常!下面是代码:

供应商:

export default class OffersGridProvider extends React.Component {    
  constructor(props) {
    super(props)
    this.store = createStore(reducers, applyMiddleware(thunk));
  }

  render() {
    return (
      <Provider store={this.store}>
        <OffersGridContainer offers={this.props.offers} />
      </Provider>
    );
  }
}

容器:

class OffersGridContainer extends React.Component {
  componentDidMount() {
    const destinationIds = this.props.offers.reduce((acc, offer) => {
      return [...acc, ...offer.to.map(d => d.destination)];
    }, []);

    this.props.getDestinations(destinationIds);
  }

  render() {
    return (
      <OffersGridLayout destinations={this.props.destinations} />
    );
  }
}

const mapStateToProps = function(store) {
  return {
    destinations: store.offersGridState.destinations
  };
}

const mapDispatchToProps = function(dispatch) {
  return {
    getDestinations: function(ids) {
      return dispatch(destinationsApi.getDestinations(ids));
    }
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(OffersGridContainer);

API方法:

export function getDestinations(ids) {
  return function(dispatch) {
    const url = $('meta[name="site-url"]').attr('content');

    const filter = ids.map((id) => {
      return `filter[post__in][]=${id}`;
    }).join('&');

    return axios.get(`${url}/wp-json/wp/v2/destinations?filter[posts_per_page]=-1&${filter}`)
      .then(response => {
        return dispatch(getOffersGridSuccess(response.data));
      });
  }
}
1个回答

建议您不要直接在组件中进行 api 调用,而是使用redux-thunkpackage.json 。

接下来,您应该将mapDispatchToProps函数作为第二个参数传递connect函数,以将动作创建器函数注入组件:

import { getDestinations } from '../actions';

class OffersGridContainer extends React.Component {    
  componentDidMount() {
    // Tip.
    const destinationIds = this.props.offers.reduce((acc, offer) => {
      return [...acc, ...offer.to.map(d => d.destination)];
    }, []);

    // instead `destinationsApi.getDestinations(dispatch, destinationIds)`
    // call action creator function
    this.props.getDestinations(destinationIds);
  }

  render() {
    return (
      <OffersGridLayout destinations={this.props.destinations} />
    );
  }
}

const mapStateToProps = function(store) {
  return {
    destinations: store.offersGridState.destinations
  };
}

const mapDispatchToProps = function(dispatch) {
  return {
    // this function will be available in component as   
    // `this.props.getDestinations`.
    getDestinations: function(destinationIds) {
      dispatch(getDestinations(destinationIds));
    }
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(OffersGridContainer);