【问题标题】:Firing Redux actions in response to route transitions in React Router触发 Redux 操作以响应 React Router 中的路由转换
【发布时间】:2015-09-24 22:49:42
【问题描述】:

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

基本上,我有一个组件需要在每次 url 更改时更新它的状态。状态正在通过带有装饰器的 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 中的 url 更改时,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);
    }
  }

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

【问题讨论】:

    标签: reactjs redux react-router


    【解决方案1】:

    好吧,我最终在 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 select={state => ({ filter: getFilters(store.router.params) })} />
    

    问题的第二部分是你需要一种方法来对视图层之外的 Redux 状态变化做出反应,比如触发一个动作来响应路由变化。如果您愿意,您可以继续将 componentWillReceiveProps 用于您描述的简单案例。

    不过,对于更复杂的事情,如果您愿意,我建议您使用 RxJS。这正是 observables 的设计目的——反应式数据流。

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

    按照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())的相同功能要简单得多。

    【讨论】:

    【解决方案2】:

    如前所述,解决方案分为两部分:

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

    为此,您只需设置react-router-redux。按照说明进行操作,您会没事的。

    一切都设置好后,你应该有一个routing 状态,像这样:

    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>>
    }
    

    您要做的是观察商店的变化,以便在发生变化时dispatch操作。

    正如@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)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-02
      • 2023-03-12
      • 2018-02-17
      • 2016-09-21
      • 2016-09-02
      • 2020-08-13
      • 2016-10-17
      • 2016-03-16
      相关资源
      最近更新 更多