【问题标题】:Defining a type for state and action Typescript为状态和动作定义类型
【发布时间】:2021-05-24 10:20:24
【问题描述】:

我在一个打字稿文件中使用状态和动作,它看起来像这样:

export const CartReducer = (state, action) => {
     switch (action.type) {
         case "ADD_ITEM":
             if (!state.cartItems.find(item => item.id === action.payload.id)) {
                 state.cartItems.push({
                     ...action.payload,
                     quantity: 1
                 })
             } 
 
             return {
                 ...state,
                 ...sumItems(state.cartItems),
                 cartItems: [...state.cartItems]
             }
         case "REMOVE_ITEM":
             return {
                 ...state,
                 ...sumItems(state.cartItems.filter(item => item.id !== action.payload.id)),
                 cartItems: [...state.cartItems.filter(item => item.id !== action.payload.id)]
             }
         case "INCREASE":
             state.cartItems[state.cartItems.findIndex(item => item.id === action.payload.id)].quantity++
             return {
                 ...state,
                 ...sumItems(state.cartItems),
                 cartItems: [...state.cartItems]
             }
         case "DECREASE":
             state.cartItems[state.cartItems.findIndex(item => item.id === action.payload.id)].quantity--
             return {
                 ...state,
                 ...sumItems(state.cartItems),
                 cartItems: [...state.cartItems]
             }
         case "CLEAR":
                 return {
                     cartItems: [],
                     ...sumItems([]),
                 }
         default:
             return state
 
     }
 }

我收到以下错误:

src/contexts/CartReducer.tsx:28:30
TS7006: Parameter 'state' implicitly has an 'any' type.
    26 |  }

我不确定如何为 State 和 Action 定义类型,虽然我已经为其他元素声明了类型,但我对 State 和 Action 的类型不一样。

我正在尝试关注this,进行打字稿项目。

【问题讨论】:

    标签: reactjs typescript react-context


    【解决方案1】:

    我相信你需要定义一个 InitialState

    initialState = {
    cartItems:[]
    }
    
    export const CartReducer = (state=initialState , action) => {
     switch (action.type) {
    

    【讨论】:

      【解决方案2】:

      您正在关注纯 JS 项目,请尝试关注 typescript 项目。

      interface MyState {
        readonly cartItems: readonly any[];
        ...
      }
      type Reducer<T> = (currentState: T, action: { type: string, payload: any })
      
      export const CartReducer: Reducer<MyState> = (state, action) => { ... }
      

      尝试为 React 寻找 reducer/action 的类型。比重新发明轮子要好。

      【讨论】:

        猜你喜欢
        • 2012-07-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-05
        • 2014-09-01
        • 2022-01-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多