数据是动态提供的,我不知道它在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;发布于 2022-06-09 10:50:48
因此,您的状态首先是一个空对象:
const initialState = {} as any;但是,您的访问方式就好像它有一个更深层次的嵌套结构一样:
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 };https://stackoverflow.com/questions/72556978
复制相似问题