【问题标题】:How to have combineReducers and custom reducers in Redux?如何在 Redux 中使用 combineReducers 和自定义 reducer?
【发布时间】:2020-10-01 16:39:48
【问题描述】:

目前,我所有的 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)
    } 
}

【问题讨论】:

    标签: reactjs typescript redux react-redux


    【解决方案1】:

    可以以这种方式组合 reducer,但解决问题的一个更简单的方法是在你的操作中获取 redux 存储的快照并将你需要的状态切片传递给你的发货时减速机。例如,如果您使用redux-thunk,则以下模式应该可以工作:

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

    【讨论】:

    • 使用联合减速器的方法是什么?这是个好主意,但不幸的是我认为它不太适用于我的情况
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-05
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 2018-12-15
    • 2018-12-10
    • 1970-01-01
    相关资源
    最近更新 更多