【问题标题】:How to add properties to react-router-redux LOCATION_CHANGE?如何向 react-router-redux LOCATION_CHANGE 添加属性?
【发布时间】:2018-10-06 10:07:36
【问题描述】:

我正在使用react-router-redux 编写应用程序。当LOCATION_CHANGE 动作被调度时,我想更新 UI 以根据用户在调查中的距离来显示进度。我的州有这样的结构:

ui: {
  progress: 0
},
survey: {
  question1: true,
  question2: null
}

我有一个函数可以遍历调查属性中的问题,并且可以根据问题的第一个实例null 确定进度。在上面的示例中,进度将为 1,因为 question2 是 null(尚待回答)。

为了更新 UI,我有一个订阅了 @@router/LOCATION_CHANGE 操作的 UI 缩减器,我可以在其中运行函数来确定进度。

我面临的问题是,在 UI reducer 中,我只能访问来自 LOCATION_CHANGE 的 UI 状态和有效负载,而不是调查。

是否可以修改 LOCATION_CHANGE 以在其有效负载中包含其他属性?

【问题讨论】:

    标签: redux react-redux react-router-redux


    【解决方案1】:

    在我看来,解决您的问题的最佳方法是使用中间件拦截所有 @@router/LOCATION_CHANGE 操作并在逻辑到达减速器之前执行您的逻辑。您可以在中间件中使用getState 函数,因此您可以读取uisurvery 状态。

    中间件

    export default ({ dispatch, getState }) => (next) => (action) => {
      if (action.type === '@@router/LOCATION_CHANGE') {
        const state = getState(); // this is the whole redux state
        const progress = getNewProgressValue(state);
        dispatch(updateProgress(progress)); // updateProgress is the action creator to update progress value
      }
      next(action);
    }
    

    您还需要根据updateProgress 动作创建者调度的动作修改您的reducer 以更新progress

    注意:我假设您没有使用redux-saga。如果你是,你仍然可以从这个方法中得到灵感。

    【讨论】:

      猜你喜欢
      • 2016-11-11
      • 2020-06-14
      • 2018-02-21
      • 2021-10-08
      • 1970-01-01
      • 2016-06-23
      • 1970-01-01
      • 2018-01-05
      • 2015-12-24
      相关资源
      最近更新 更多