在React Router中触发Redux操作以响应路由转换

reactjs React.js

逆天前端宝儿

2020-04-07

我在最新的应用程序中使用react-router和redux,并且遇到了一些与基于当前url参数和查询所要求的状态更改有关的问题。

基本上,我有一个组件,每次URL更改时都需要更新其状态。像这样通过 decorator通过redux通过props传递状态

 @connect(state => ({
   campaigngroups: state.jobresults.campaigngroups,
   error: state.jobresults.error,
   loading: state.jobresults.loading
 }))

目前,我正在使用componentWillReceiveProps生命周期方法来响应来自react-router的url更改,因为当this.props.params和this.props.query中的url更改时,react-router会将新的props传递给处理程序。这种方法的主要问题是,我正在此方法中触发操作以更新状态-然后,该状态通过并传递新的props该组件将再次触发相同的生命周期方法-因此基本上创建了一个无穷循环,目前我正在设置一个状态变量以阻止这种情况的发生。

  componentWillReceiveProps(nextProps) {
    if (this.state.shouldupdate) {
      let { slug } = nextProps.params;
      let { citizenships, discipline, workright, location } = nextProps.query;
      const params = { slug, discipline, workright, location };
      let filters = this._getFilters(params);
      // set the state accroding to the filters in the url
      this._setState(params);
      // trigger the action to refill the stores
      this.actions.loadCampaignGroups(filters);
    }
  }

是否有基于路线转换触发动作的标准方法,还是可以将商店的状态直接连接到组件的状态,而不是通过prop传递它?我尝试使用willTransitionTo静态方法,但无法访问this.props.dispatch。

第4049篇《在React Router中触发Redux操作以响应路由转换》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

0个回答

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android