【问题标题】:Redux nested duplicate properties are creatingRedux 嵌套重复属性正在创建
【发布时间】: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-&gt; category -&gt; Array & store-&gt; brands -&gt; Array

【问题讨论】:

  • category 中的状态 CategoryReducer 是一个数组吗?如果是这样,那么在解构和附加类别时,您不应该使用[] 而不是{} 吗?
  • 是的@MohammadAbdulAlim 类别是一个数组。好的,我检查一下

标签: reactjs redux react-state-management


【解决方案1】:

CategoryReducer.js 中,案例“TOGGLE_CATEGORY_SELECTION”看起来像这样

return { ...state, category: [ ...state.category, ...action.payload ] }

或者如果您不想将值添加到商店中的类别数组中

return { ...state, category: action.payload }

【讨论】:

  • 嗨@Kevin TOGGLE_CATEGORY_SELECTION 此操作未触发,仅触发了UPDATE_CATEGORIES。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-09
  • 2020-12-05
  • 2017-05-26
  • 1970-01-01
相关资源
最近更新 更多