reactjs - 如何在 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)
}
}
但我不想写出所有其他减速器,就像我foo
的bar
商店只有一件需要商店的其他部分一样。有没有办法将自定义减速器组合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)
}
}
解决方案
可以以这种方式组合 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 })
}
}
推荐阅读
- c# - FindViewById 返回 null(只有一个,在 OnCreate 内部和 SetContentView 之后)
- javascript - javascript 使用 appendChild 出现具有特定 ID 的事物
- vba - 引用在不同模块中创建的控制对象
- java - 继承 - 调用什么方法?
- linux - lua redis 处理错误
- python - 如何将输入矩阵拆分为子矩阵以进行并行 GPU 处理?
- amazon-dynamodb - 如何查询 DynamoDb 中的对象列表(使用 CLI)
- asp.net-mvc - 不支持关键字:“元数据”。尝试创建动态连接字符串时
- sql - 将数据类型 varchar 转换为 int 动态 SQL 选择语句时出错
- javascript - Nodejs Mongoose:尝试在 UTC 时区保存日期,但在本地时区保存