簡體   English   中英

如何使用 redux 工具包改變狀態

[英]How to mutate state with redux toolkit

數據是動態提供的,我不知道在 initialState 中分配它的值。 它給我帶來了一個我無法處理的錯誤。

如果initialState中沒有對象,如何更新狀態中的對象?

錯誤

filteringSlice.ts:12 

Uncaught TypeError: Cannot read properties of undefined (reading 'products')
    at addFilter (filteringSlice.ts:12:1)
    at createReducer.ts:280:1
    at produce (immerClass.ts:94:1)
    at createReducer.ts:279:1
    at Array.reduce (<anonymous>)
    at reducer (createReducer.ts:246:1)
    at reducer (createSlice.ts:325:1)
    at combination (redux.js:560:1)
    at k (<anonymous>:2235:16)
    at D (<anonymous>:2251:13)

呼叫行動

onChange={(selectedValue) => {
  dispatch(
    addFilter({
      products: { category__name: { filter: selectedValue } },
    })
  );
}}

import { createSlice } from "@reduxjs/toolkit";
const initialState = {} as any;
const filteringSlice = createSlice({
  name: "filtering",
  initialState,
  reducers: {
    addFilter: (state, action) => {
      const key = Object.keys(action.payload)[0];
      const key2 = Object.keys(action.payload[key])[0];
      const values = Object.values(action.payload[key])[0];
      //@ts-ignore
      state.filters[key][key2] = { ...state.filters[key][key2], ...values };
    },
  },
});
const { reducer, actions } = filteringSlice;
export const { addFilter } = actions;
export default reducer;

所以你的狀態起初是一個空對象:

const initialState = {} as any;

但是然后您訪問 at 就好像它具有更深的嵌套結構:

state.filters[key][key2] = ...

這不起作用,因為沒有state['filters'] ,也沒有state['filters']['products']等。

您需要手動創建此嵌套的每個級別才能使其正常工作(或為您的狀態考慮更好、更扁平的結構):

/*
action.payload = {
  products: {
    category__name: {
      filter: selectedValue
    }
  }
}
*/
const key = Object.keys(action.payload)[0]; // 'products'
const key2 = Object.keys(action.payload[key])[0]; // 'category__name'
const values = Object.values(action.payload[key])[0]; // selectedValue

if (!state.filters) {
  state.filters = {};
}
if (!state.filters[key]) {
  state.filters[key] = {}; 
}
if (!state.filters[key][key2]) {
    state.filters[key][key2] = {};
}

state.filters[key][key2] = { ...state.filters[key][key2], ...values };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM