redux-toolkit -- Type error: "unit" is read-only

redux-toolkit -- Type error: "unit" is read-only

我正在为这个项目使用 react-redux 和 redux-toolkit。我想将商品添加到购物车。如果购物车中已经有相同的商品,只需增加单位。错误出现在slice处,所以这里就直接显示slice。


const CartListSlice = createSlice({
    name: 'cartItem',
    initialState,
    reducers: {
      addToCart: (state, action) => {
        let alreadyExist = false;
// get a copy of it to avoid mutating the state
        let copyState = current(state.cartItem).slice();
        // loop throught the cart to check if that item is already exist in the cart
        copyState.map(item => {
              if (item.cartItem._id === action.payload._id) {
                alreadyExist = true;
                item.unit += 1  // <--- Error occurs here
              }
            })
        
// If the item is not exist in the cart, put it in the cart and along with its unit
        if (alreadyExist === false) {
          state.cartItem.push({
            cartItem: action.payload, 
            unit: 1
          });
        }
      },
    }
});

我收到一个类型错误,告诉我 unit 是只读的。 我怎样才能更新“单位”变量,以便它在应该的时候递增。

在 React Toolkit 的 createSlice 中,您可以直接修改 state,甚至应该这样做。所以不要创建副本,只需修改它。 事实上,这个错误可能在某种程度上源于使用 current.

制作副本

See the "Writing Reducers with Immer" documentation page on this

同时提个建议:

const CartListSlice = createSlice({
    name: 'cartItem',
    initialState,
    reducers: {
      addToCart: (state, action) => {
        const existingItem = state.find(item => item.cartItem._id === action.payload._id)
        if (existingItem) {
          item.unit += 1
        } else {
          state.push({
            cartItem: action.payload, 
            unit: 1
          });
        }
      },
    }
});

你不需要线路:

let copyState = current(state.cartItem).slice();

而不是copyState,只需使用state.cartItem.map

正如@phry 所说,你应该直接改变 state,因为 redux-toolkit 在后台使用 immerJS 来处理突变。