javascript 未捕获的类型错误:无法读取未定义的属性(阅读“push”),使用addToCart时出错

9rygscc1  于 2023-10-14  发布在  Java
关注(0)|答案(1)|浏览(94)
import { createSlice } from '@reduxjs/toolkit';

    const cartSlice = createSlice({
    name: 'cart',
    initialState: {
    items: [],
    },
    reducers: {
    addToCart: (state, action) => {
      state.items.push(action.payload);
    },
    removeFromCart: (state, action) => {
      state.items = state.items.filter(item => item.id !== action.payload.id);
    },
    clearCart: state => {
      state.items = [];
    },
    },
    });

export const { addToCart,removeFromCart,clearCart } = cartSlice.actions;
导出默认cartSlice.reducer;
当我将initialstate定义为数组(initialstate =[])并执行操作(state.push(...))时,它正在工作。

56lgkhnf

56lgkhnf1#

问题

这里的问题似乎是,你曾经有一个购物车切片可能看起来像下面这样:

const initialState = [];

const cartSlice = createSlice({
  name: "cart",
  initialState,
  reducers: {
    addToCart: (state, action) => {
      state.push(action.payload);
    },
    removeFromCart: (state, action) => {
      return state.filter((item) => item.id !== action.payload.id);
    },
    clearCart: (state) => {
      return [];
    }
  }
});

这个slice/reducer产生的状态被持久化到localStorage。
范例:

"persist:root": "{"cart":"[{\"id\":\"_DX4ebWHrqY1R6iVevCLV\"},{\"id\":\"JTqqLWDHTyCbk4gSroFYX\"}]","_persist":"{\"version\":-1,\"rehydrated\":true}"}"

然后你 * 改变了 * cart slice reducers来生成一个 * 不同的 * 状态形状:

const initialState = {
  items: []
};

const cartSlice = createSlice({
  name: "cart",
  initialState,
  reducers: {
    addToCart: (state, action) => {
      state.items.push(action.payload);
    },
    removeFromCart: (state, action) => {
      state.items = state.items.filter((item) => item.id !== action.payload.id);
    },
    clearCart: (state) => {
      state.items = [];
    }
  }
});

但是先前的状态形状仍然存在于localStorage中,并且作为状态值被重新水合,并且由于当前状态值与reducer/selectors引用的值之间存在不匹配,因此会产生错误。

解决方案

重置保存的持久化状态

如果你不关心或需要保存现有的状态,那么你可以简单地从localStorage中删除persist:root键/值,然后重新加载应用。由于现在将没有持久化状态来水合应用状态,因此来自Reducer的初始状态将使用当前初始状态值计算初始状态树。

  • 打开浏览器的开发工具
  • 导航到“应用程序”选项卡
  • 找到localStorage部分
  • 删除"persist:root"条目
  • 重新加载应用程序

迁移旧状态到新状态

创建一个migration,从旧的、不正确的状态转换为新的当前状态形状。

import { configureStore, combineReducers } from "@reduxjs/toolkit";
import { createMigrate, persistStore, persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage";
import cartReducer from "./cart.slice";

const migrations = {
  // Move state.cart to state.cart.items
  0: (state) => {
    const { cart, ...newState } = state;
    return {
      ...newState,
      cart: {
        items: cart
      }
    };
  }
};

const rootReducer = combineReducers({
  cart: cartReducer
  auth: authReducer
});

const persistConfig = {
  key: "root",
  storage,
  version: 0, // <-- set state version
  migrate: createMigrate(migrations, { debug: true }) // <-- debug true if you want to see logs, otherwise set false
};

const persistedReducer = persistReducer(persistConfig, rootReducer);

const store = configureStore({
  reducer: persistedReducer
});

const persistor = persistStore(store);

export { store, persistor };

相关问题