gpt4 book ai didi

javascript - Redux:从combineReducers和 "loose"属性创建根reducer

转载 作者:行者123 更新时间:2023-12-03 13:33:10 25 4
gpt4 key购买 nike

我想创建一个具有以下形状的 Redux 存储:

store = {
loaded: Boolean,
loading: Boolean,
view: Object, // uses combineReducers
layers: Object // uses combineReducers
}

到目前为止,我的根 reducer 看起来像这样:

rootReducer.js

import view from './view';
import layers from './layers';

const initialState = {
loaded: false,
loading: false,
};

function loadState(state = initialState, action = {}) {
switch (action.type) {
case 'LOADED':
return {
...state,
loaded: true,
loading: false,
};

case 'LOADING':
return {
...state,
loaded: false,
loading: true,
};

default:
return state;
}
}

export default combineReducers({
view,
layers,
// hmmmm, putting loadState here would give me a loadState object property,
// not loose 'loaded' and 'loading' properties
});

如何同时拥有这些“松散”属性,例如 loadedloading

最佳答案

有时,我发现为一些简单的属性编写单独的 reducer 会带来令人讨厌的开销,因此我有时会使用一个 combineReducersWithRoot 实用程序。

export function combineReducersWithRoot(rootReducer, reducers) {
return (state, action) => {
// Ensure the root state object is a new object; otherwise
// React may not re-render.
let newState = {...rootReducer(state, action)};
Object.keys(reducers).forEach(domain => {
let obj = state ? state[domain] : undefined;
newState[domain] = reducers[domain](obj, action);
});
return newState;
};
}

现在,给定一个类似这样的状态结构:

{
loading: bool
loaded: bool
data: {
filter: string
arr: object[]
}
}

你可以这样做:

function rootReducer(state = {loading: false, loaded: false}, action) {
switch(action.type) {
case STARTED_LOADING:
return {...state, loading: true, loaded: false};
case FINISHED_LOADING:
return {...state, loading: false, loaded: true};
default:
return state;
}
}

function dataReducer(state = {filter: '', arr: []}, action) {
switch (action.type) {
case SET_FILTER:
return {...state, filter: action.value};
case SET_DATA:
return {...state, arr: action.arr};
default:
return state;
}
}

export default combineReducersWithRoot(rootReducer, {data: dataReducer});

关于javascript - Redux:从combineReducers和 "loose"属性创建根reducer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39261092/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com