首页 文章

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

提问于
浏览
52

我在我的最新应用程序中使用react-router和redux,我面临一些与基于当前url参数和查询所需的状态更改有关的问题 .

基本上我有一个组件,每次url更改时都需要更新它的状态 . 正在通过redux通过道具传递状态,装饰器就像这样

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

目前我正在使用componentWillReceiveProps生命周期方法来响应来自react-router的url更改,因为当url在this.props.params和this.props.query中更改时,react-router会将新的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);
    }
  }

是否存在基于路由转换触发操作的标准方法或者我可以将存储的状态直接连接到组件的状态而不是通过props传递它吗?我曾尝试使用willTransitionTo静态方法,但我无法访问this.props.dispatch .

2 回答

  • 36

    好吧,我最终在redux的github页面上找到了答案,所以会在这里发布 . 希望它能为某些人带来一些痛苦 .

    @deowk我会说,这个问题有两个部分 . 第一个是componentWillReceiveProps()不是响应状态变化的理想方式 - 主要是因为它迫使你强制思考,而不是像我们使用Redux那样被动地反应 . 解决方案是将您当前的路由器信息(位置,参数,查询)存储在您的商店中 . 然后您所有的州都在同一个地方,您可以使用与其他数据相同的Redux API订阅它 .

    诀窍是创建一个在路由器位置发生变化时触发的动作类型 . 在即将推出的1.0版React Router中很容易:

    // routeLocationDidUpdate() is an action creator
    // Only call it from here, nowhere else
    BrowserHistory.listen(location => dispatch(routeLocationDidUpdate(location)));
    

    现在,您的商店状态将始终与路由器状态同步 . 这修复了在上面的组件中手动响应查询参数更改和setState()的需要 - 只需使用Redux的Connector .

    <Connector select={state => ({ filter: getFilters(store.router.params) })} />
    

    问题的第二部分是您需要一种方法来响应视图层之外的Redux状态更改,比如触发响应路由更改的操作 . 如果您愿意,可以继续使用componentWillReceiveProps来处理您描述的简单情况 .

    但是,对于任何更复杂的事情,如果你对它开放,我建议使用RxJS . 这正是observables的设计目标 - 反应式数据流 .

    要在Redux中执行此操作,请首先创建一个可观察的存储状态序列 . 你可以使用rx的observableFromStore()来做到这一点 .

    EDIT AS SUGGESTED BY CNP

    import { Observable } from 'rx'
    
    function observableFromStore(store) {
      return Observable.create(observer =>
        store.subscribe(() => observer.onNext(store.getState()))
      )
    }
    

    然后,只需使用可观察的运算符来订阅特定的状态更改 . 以下是成功登录后从登录页面重定向的示例:

    const didLogin$ = state$
      .distinctUntilChanged(state => !state.loggedIn && state.router.path === '/login')
      .filter(state => state.loggedIn && state.router.path === '/login');
    
    didLogin$.subscribe({
       router.transitionTo('/success');
    });
    

    这种实现比使用命令式模式(如componentDidReceiveProps())的相同功能简单得多 .

  • 8

    如前所述,该解决方案包含两部分:

    1)将路由信息链接到状态

    为此,您所要做的就是设置react-router-redux . 按照说明你会没事的 .

    设置完所有内容后,您应该具有 routing 状态,如下所示:

    state

    2)观察路由更改并触发操作

    你代码中的某个地方现在应该有这样的东西:

    // find this piece of code
    export default function configureStore(initialState) {
        // the logic for configuring your store goes here
        let store = createStore(...);
        // we need to bind the observer to the store <<here>>
    }
    

    你想要做的是观察商店中的变化,这样你就可以在事情发生变化时采取行动 .

    正如@deowk所提到的,你可以使用 rx ,或者你可以编写自己的观察者:

    reduxStoreObserver.js

    var currentValue;
    /**
     * Observes changes in the Redux store and calls onChange when the state changes
     * @param store The Redux store
     * @param selector A function that should return what you are observing. Example: (state) => state.routing.locationBeforeTransitions;
     * @param onChange A function called when the observable state changed. Params are store, previousValue and currentValue
     */
    export default function observe(store, selector, onChange) {
        if (!store) throw Error('\'store\' should be truthy');
        if (!selector) throw Error('\'selector\' should be truthy');
        store.subscribe(() => {
            let previousValue = currentValue;
            try {
                currentValue = selector(store.getState());
            }
            catch(ex) {
                // the selector could not get the value. Maybe because of a null reference. Let's assume undefined
                currentValue = undefined;
            }
            if (previousValue !== currentValue) {
                onChange(store, previousValue, currentValue);
            }
        });
    }
    

    现在,您所要做的就是使用我们刚写的 reduxStoreObserver.js 来观察变化:

    import observe from './reduxStoreObserver.js';
    
    export default function configureStore(initialState) {
        // the logic for configuring your store goes here
        let store = createStore(...);
    
        observe(store,
            //if THIS changes, we the CALLBACK will be called
            state => state.routing.locationBeforeTransitions.search, 
            (store, previousValue, currentValue) => console.log('Some property changed from ', previousValue, 'to', currentValue)
        );
    }
    

    上面的代码使我们的函数在每次locationBeforeTransitions.search在状态中发生变化时被调用(作为用户导航的结果) . 如果需要,可以观察que查询字符串等 .

    如果您想通过路由更改触发操作,则您只需在处理程序内部 store.dispatch(yourAction) .

相关问题