【问题标题】:Reset state = initialState not working for me in redux重置状态 = initialState 在 redux 中对我不起作用
【发布时间】:2023-01-15 08:46:48
【问题描述】:

我想使用以下代码重置状态。但我不知道为什么它会给我错误 'initialState' is not defined。请帮我解决这个问题。非常感谢。

import { createSlice } from '@reduxjs/toolkit';

const cartSlice = createSlice({
  name: 'cart',
  initialState:
    // JSON.parse(localStorage.getItem('item')) ||
    {
      products: [],
      quantity: 0,
      total: 0,
    },
  reducers: {
    addProduct: (state, action) => {
      state.products.push(action.payload);
      state.quantity += 1;
      state.total += action.payload.price * action.payload.quantity;
      // localStorage.setItem('item', JSON.stringify(state));
    },
    deleteItem: (state, action) => {
      state.quantity -= 1;
      state.total -= action.payload.price * action.payload.quantity;
    },
    reset: (state) => {
      state = initialState;
    },
  },
});

export const { addProduct, reset, deleteItem } = cartSlice.actions;
export default cartSlice.reducer;

Error here

【问题讨论】:

    标签: javascript reactjs redux redux-toolkit


    【解决方案1】:

    state = something绝不适用于 RTK 减速机。您可以修改变量state中的对象,不能将变量state重新分配给新对象。

    return something而不是state = something。这在 Writing Reducers with immer 文档页面中有描述。

    【讨论】:

      【解决方案2】:

      您必须手动声明初始状态才能重置状态。

      import { createSlice } from '@reduxjs/toolkit';
      
      const cartSlice = createSlice({
        name: 'cart',
        initialState:
          // JSON.parse(localStorage.getItem('item')) ||
          {
            products: [],
            quantity: 0,
            total: 0,
          },
        reducers: {
          addProduct: (state, action) => {
            state.products.push(action.payload);
            state.quantity += 1;
            state.total += action.payload.price * action.payload.quantity;
            // localStorage.setItem('item', JSON.stringify(state));
          },
          deleteItem: (state, action) => {
            state.quantity -= 1;
            state.total -= action.payload.price * action.payload.quantity;
          },
          reset: (state) => {
            state = {
            products: [],
            quantity: 0,
            total: 0,
          };
          },
        },
      });
      
      export const { addProduct, reset, deleteItem } = cartSlice.actions;
      export default cartSlice.reducer;
      

      【讨论】:

      • 哦,我明白了。有用。非常感谢 <3
      【解决方案3】:

      您根本没有初始化 initialState。您可以将 initialState 从切片中拉出,它应该可以工作。

      import { createSlice } from '@reduxjs/toolkit';
      
      const initialState = {
            products: [],
            quantity: 0,
            total: 0,
          };
      
      const cartSlice = createSlice({
        name: 'cart',
        initialState:
          // JSON.parse(localStorage.getItem('item')) ||
          initialState
        reducers: {
          addProduct: (state, action) => {
            state.products.push(action.payload);
            state.quantity += 1;
            state.total += action.payload.price * action.payload.quantity;
            // localStorage.setItem('item', JSON.stringify(state));
          },
          deleteItem: (state, action) => {
            state.quantity -= 1;
            state.total -= action.payload.price * action.payload.quantity;
          },
          reset: (state) => {
            state = initialState;
          },
        },
      });
      
      export const { addProduct, reset, deleteItem } = cartSlice.actions;
      export default cartSlice.reducer;
      

      【讨论】:

      • 但是添加数据时初始状态值会改变,所以不能重置?
      【解决方案4】:

      如果您使用的是 redux 工具包……这就是您的操作方式……

      import { createSlice } from "@reduxjs/toolkit";
      import { getStringArray } from "../helperFunctions";
      const initialState = {
        game: {
          MODAL_OPEN: false,
          END: false,
          PLAYING: false,
          LEVEL: 1,
          WON: false,
          LOST: false,
          wordLength: 5,
          RANDOM_WORD: "",
          colIndex: 0,
          rowIndex: 0,
          ATTEMPTS: 6,
          darkMode: false,
          INIT: false,
        },
        ROW_ARRAY: new Array(6).fill(new Array(5).fill({ value: "", color: "" })),
        ROW_ARRAY_NEW: new Array(6).fill(
          new Array(5).fill({ value: "", color: "#ddd" })
        ),
      };
      
      const gameSlice = createSlice({
        name: "game",
        initialState: initialState,
        reducers: {
          resetGame: (state) => (state = initialState),

      【讨论】:

        【解决方案5】:

        它通过返回 initialState 而不是分配它来为我工作。像这样:

        reset: (state) => {
          return initialState; // INSTEAD OF THIS state = initialState;
        }
        

        【讨论】:

          猜你喜欢
          • 2018-07-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-11-07
          • 1970-01-01
          • 2020-12-14
          • 2021-10-15
          • 2020-07-14
          相关资源
          最近更新 更多