为什么即使我修改了草稿,Immer 也没有 return 给我一个新的状态?

Why Immer didn't return me a new state even if I modified the draft?

不知道为什么我修改了草稿,immer给我提供的不是新状态,而是修改内容后的旧状态实例。

import CartItem from "../../models/cart-item";
import * as actions from "../actions/actionTypes";
import produce from "immer"


const initialState = [];

const reducer = (state=initialState, action) => {
    switch (action.type) {
        case actions.ADD_TO_CART:
          const {id, title, price} = action.product;
          const itemIndexInCart = state.findIndex(item => item.id === id);

          const nextState = produce(state, draftState => {
            if (itemIndexInCart === -1) {
              draftState.push(new CartItem(id, 1, price, title, price));
            } else {
              draftState[itemIndexInCart]['quantity']++;
              draftState[itemIndexInCart]['sum'] += price;
            }
          });
          console.log(state === nextState);
          return nextState;
        default:
            return state;
    }
};

export default reducer;

新项推入数组时可以,但是当我想修改数组项的数量和总和时,它没有按预期工作。日志显示在那种情况下它是同一个对象。

根据 docs,诀窍是让您的 class 身临其境。 请注意,console.logging 草稿可能会打印“null”,即使此对象不为 null。

import {immerable} from "immer"

class Foo {
    [immerable] = true // Option 1

    constructor() {
        this[immerable] = true // Option 2
    }
}

Foo[immerable] = true // Option 3

工作演示:https://codesandbox.io/s/blissful-resonance-v6v9b?file=/src/App.js

注意 you should never put non-serializable values like class instances into the Redux store.

此外,您应该使用our official Redux Toolkit package,这将让您简化现有的 Redux 逻辑。例如,这个减速器可以写成:

const cartSlice = createSlice({
  name: "cart",
  initialState: [],
  reducers: {
    addToCart(state, action) {
      const {id, title, price} = action.payload;
      const item = state.find(item => item.id === id);
      
      if(item) {
        item.quantity++;
        item.sum += price;
      } else {
        state.push({id, price, title, quantity: 1});
      }
    }
  }
})