Redux Toolkit 1.9.3和'Property 'push'在类型'WritableDraft '上不存在< CartState>

92vpleto  于 2023-03-23  发布在  其他
关注(0)|答案(1)|浏览(114)

尝试使用TypeScript的ReduxToolkit,我被一些我怀疑非常简单/明显的东西难倒了。然而,我不知道足够的东西来弄清楚,需要一些指导。
基本上我得到了一个**属性'push' does not exist on type 'WritableDraft'.**错误在下面的代码:

import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import { Product } from '../pages/Product/Types'

export interface CartState {
  products: Product[]
}

const initialState: CartState = {
  products: []
}

export const cartSlice = createSlice({
  name: 'cart',
  initialState,
  reducers: {
    addToCart: (state, action: PayloadAction<Product>) => {
      state.push(action.payload) <=== ERROR HERE, WITH 'push'
    }
  }
})

// Action creators are generated for each case reducer function
// export const { addToCart, decrement, incrementByAmount } = cartSlice.actions
export const { addToCart } = cartSlice.actions

export default cartSlice.reducer

我知道push()不起作用是因为state不被认为是一个数组,但我不知道如何解决这个问题,因为这里已经有了代码。谢谢!

btqmn9zl

btqmn9zl1#

您的购物车状态有一个您缺少的products字段:

export const cartSlice = createSlice({
  name: 'cart',
  initialState,
  reducers: {
    addToCart: (state, action: PayloadAction<Product>) => {
      state.products.push(action.payload)
//          ~~~~~~~~
    }
  }
})

Playground

相关问题