首页 > 解决方案 > 如何在 Redux 中使用 combineReducers 和自定义 reducer?

问题描述

目前,我所有的 reducer 只需要状态值中的数据,所以我的“rootReducer”看起来像这样

export const appReducer = combineReducers({ foo: fooReducerFunction, bar: barReducerFunction})

这很好,但现在我有一个需要状态的其他部分的减速器,我知道可以这样完成

export function App(state: AppState, action: AppActions): AppState {
    return {
       foo: fooReducerFunction(state.foo, action),
       bar: fooReducerFunction(state.bar, action),
       baz: bazReducerFunction({foo: state.foo, bar: state.bar}, action)
    } 
}

但我不想写出所有其他减速器,就像我foobar商店只有一件需要商店的其他部分一样。有没有办法将自定义减速器组合combineReducers成这样的东西?

const appReducer = combineReducers({ foo: fooReducerFunction, bar: barReducerFunction})

export function App(state: AppState, action: AppActions): AppState {
    return {
       ...appReducer,
       baz: bazReducerFunction({foo: state.foo, bar: state.bar}, action)
    } 
}

标签: reactjstypescriptreduxreact-redux

解决方案


可以这种方式组合 reducer,但解决问题的更简单方法是在 action 中获取 redux 存储的快照,并在调度时将所需的状态切片传递给 reducer。redux-thunk例如,如果您使用的是以下模式,则应该可以使用:

export const actionFoo = (data) =>  {
  return (dispatch, getState) => {
    // access slice of state first
    const { otherStateSlice } = getState()
    dispatch({ type: UPDATE_DATA, otherStateSlice, data })
  }
}

推荐阅读