如何使用immutable.js之类的东西在Redux中组合多个combineReducers函数 [英] How can I combine multiple combineReducers functions in Redux using something like immutable.js
问题描述
我使用immutable.JS通过redux-immutablejs管理我的商店。我现在想使用redux-form库,但我遇到了一个组合reducer的问题。
I am using immutable.JS to manage my stores via redux-immutablejs. I would now like to use the redux-form library but I am having an issue combining reducers.
Redux-immutable提供了combineReducers函数,该函数将检查传递的所有reducers是否返回不可变对象。
Redux-immutable provides a combineReducers function that will check if all the reducers it is passed return immutable objects.
Redux本身提供了combineReducers函数,不执行此类检查。
Redux itself provides a combineReducers function that performs no such checking.
Redux-form要求你包含他们的reducers但是我不能使用Redux immutable的combineReducers,因为它会失败。
Redux-form requires that you include their reducers but I cannot do so using Redux immutable's combineReducers as it will fail.
所以我要做的是基本上将这两个函数的输出结合起来如下:
So what I'm trying to do is basically combine the outputs of these two functions like so:
import { combineReducers } from 'redux';
import { combineReducers as combineReducersUtils } from 'redux-utils';
import {reducer as formReducer} from 'redux-form';
const mainReducers = combineReducersUtils({
devices, alarms
});
const extraReducers = combineReducers({
form: formReducer
});
export default (mainReducers + extraReducers);
最后一行显然不起作用,但基本上说明了我的目标。
The last line obviously doesn't work but illustrates basically what I'm after.
感谢您花时间阅读此内容。
Thanks for taking the time to read this.
推荐答案
也许是这样的?
function rootReducer(state, action) {
const newState = combineReducersUtils({devices, alarms})(state, action);
return combineReducers({form: formReducer})(newState, action);
}
它应该有效,因为combineReducers的返回值只是一个减速器:
It should work because the return value of combineReducers is just a reducer:
(函数):一个reducer,它调用reducers对象中的每个reducer,并构造一个具有相同形状的状态对象。
(Function): A reducer that invokes every reducer inside the reducers object, and constructs a state object with the same shape.
https://github.com/rackt/redux/blob/master/docs/api/combineReducers.md
更新为不在每个调度上创建新函数:
Updated to not create a new function on every dispatch:
const mainReducers = combineReducersUtils({devices, alarms});
const formReducers = combineReducers({form: formReducer});
function rootReducer(state, action) {
return formReducers(mainReducers(state, action), action);
}
这篇关于如何使用immutable.js之类的东西在Redux中组合多个combineReducers函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!