【发布时间】:2021-05-16 04:23:45
【问题描述】:
我将数据存储在 Redux 存储中,但不是更新存储属性,而是创建嵌套副本
Index.js
const initialStore = {
user: {},
brands: [],
category: []
}
ReactDOM.render(
<Provider store={configureStore(initialStore)}>
<App />
</Provider>,
document.getElementById('root')
);
Store.js
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers/rootReducer';
const enhancers = [];
const middleware = [
thunk
];
const windowIfDefined = typeof window === 'undefined' ? null : window;
if (windowIfDefined && windowIfDefined.__REDUX_DEVTOOLS_EXTENSION__) {
enhancers.push(windowIfDefined.__REDUX_DEVTOOLS_EXTENSION__());
}
export default function configureStore(initialState = {}) {
return createStore(
rootReducer,
initialState,
compose(applyMiddleware(...middleware), ...enhancers)
);
}
RootReducer.js
import { combineReducers } from 'redux';
import brandsReducer from './brandsReducer';
import userReducer from "./userReducer";
import categoryReducer from "./categoryReducer";
export default combineReducers({
brands: brandsReducer,
user: userReducer,
category: categoryReducer
});
CategoryReducer.js
export default (state = {}, action) => {
switch (action.type) {
case 'UPDATE_CATEGORIES':
return Object.assign({}, state, { category: action.payload });
case 'TOGGLE_CATEGORY_SELECTION':
return {
...state, category: { ...state.category, category: action.payload }
}
default:
return state;
}
}
我想以这种格式存储store-> category -> Array & store-> brands -> Array。
【问题讨论】:
-
category中的状态CategoryReducer是一个数组吗?如果是这样,那么在解构和附加类别时,您不应该使用[]而不是{}吗? -
是的@MohammadAbdulAlim 类别是一个数组。好的,我检查一下
标签: reactjs redux react-state-management