【问题标题】:How to access a reducer state within another reducer when we use "redux-starter-kit"?当我们使用“redux-starter-kit”时,如何访问另一个减速器中的减速器状态?
【发布时间】:2019-07-07 22:40:38
【问题描述】:

现在我使用 redux-starter-kit 制作了两个减速器(学生减速器和考试减速器)。我们如何在学生减速器中访问考试减速器的状态?还有,我们可以在student reducer中调用exam的dispatch函数来修改exam state的状态吗?

examReducer.js

const exam = createSlice({
 initialState: {
   mathScore: 0
 },
 reducer: {
   setMathScore: (state, action) => {
    state.mathScore = action.payload;
   }
 }
});

studentReducer.js

const student = createSlice({
 initialState: {
   pass: false
 },
 reducer: {
   setMathScore: (state, action) => {
    //try to get math score from exam reducer
    state.pass = /*TODO*/ > 70 ? true : false;
   }
 }
});

store.js

const store = configureStore({
  reducer: {
    exam: exam.reducer,
    student: student.reducer
  }
});

【问题讨论】:

    标签: javascript reactjs redux


    【解决方案1】:

    你不能“访问另一个 reducer 的状态”,因为这不是 Redux 的一般工作方式。 Redux Starter Kit 在这方面没有什么特别之处。

    根据Redux FAQ entry on "sharing state between reducers"

    很多用户后来想尝试在两个reducer之间共享数据,但是发现combineReducers不允许他们这样做。有几种方法可以使用:

    • 如果 reducer 需要了解来自另一个状态切片的数据,则可能需要重新组织状态树形状,以便单个 reducer 处理更多数据。
    • 您可能需要编写一些自定义函数来处理其中一些操作。这可能需要用您自己的顶级 reducer 函数替换 combineReducers。您还可以使用 reduce-reducers 等实用程序运行 combineReducers 来处理大多数操作,还可以为跨状态切片的特定操作运行更专业的 reducer。
    • redux-thunk 等异步操作创建者可以通过getState() 访问整个状态。动作创建者可以从状态中检索其他数据并将其放入动作中,以便每个 reducer 都有足够的信息来更新自己的状态切片。

    此外,您绝对不能在 reducer 内调度操作。这是禁止的,会抛出错误。

    【讨论】:

      猜你喜欢
      • 2017-07-03
      • 2019-04-20
      • 2019-11-23
      • 2016-11-24
      • 2016-04-23
      • 2019-04-11
      • 2016-10-31
      • 1970-01-01
      • 2021-10-13
      相关资源
      最近更新 更多