“未定义”类型不能分配给“道具”类型

时间:2021-05-20 15:32:32

标签: javascript reactjs typescript context-api

我有一个 ProductContext,它基本上可以帮助我轻松地传递产品。这是代码:

import React, { createContext, useState } from 'react';
import { dummyProducts } from '../constants/dummyProducts';
interface IProducts {
    id: number;
    name: string;
    price: number;
    type: string;
    photo: string;
    details: string;
}

type Props = { children: React.ReactElement }
export const ProductsContext = createContext<IProducts[]>([]);

const ProductsContextProvider = ({children} : Props) => {
    const [products] = useState(dummyProducts);
    return ( 
        <ProductsContext.Provider value={products} >
            { children }
        </ProductsContext.Provider>
     );
}
export default ProductsContextProvider;

而且我还有一个 CartContext 负责所有与 Cart 相关的操作,例如 AddToCart、Remove 等。代码如下:

import React, { createContext, useReducer } from 'react';
import { CartReducer, sumItems } from './CartReducer';

type Props = { children: React.ReactElement }
interface IProduct {
     id: number;
     name: string;
     price: number;
     type: string;
     photo: string;
     details: string;
}
type PropsForPayload = { payload: IProduct }
type ICart = {
     itemCount: number,
     removeProduct: (payload: PropsForPayload) => void,
     addProduct: (payload: PropsForPayload) => void,
     increase: (payload: PropsForPayload) => void,
     decrease: (payload: PropsForPayload) => void,
     clearCart: (payload: PropsForPayload) => void,
     handleCheckout: (payload: PropsForPayload) => void,
     cartItems: Array<any>
}
const contextDefalutValues: ICart = {
     itemCount: 0,
     removeProduct: () => { },
     addProduct: () => { },
     increase: () => { },
     decrease: () => { },
     clearCart: () => { },
     handleCheckout: () => { },
     cartItems: []
}
export const CartContext = createContext<ICart>(contextDefalutValues);



const storage = localStorage.getItem('cart') ? JSON.parse(localStorage.getItem('cart') ?? "[1]") : [];
const initialState = { cartItems: storage, ...sumItems(storage), checkout: false };

const CartContextProvider = ({ children }: Props) => {
     const [state, dispatch] = useReducer(CartReducer, initialState)
     const increase = (payload: PropsForPayload) => {
          dispatch({ type: 'INCREASE', payload })
     }
     const decrease = (payload: PropsForPayload) => {
          dispatch({ type: 'DECREASE', payload })
     }
     const addProduct = (payload: PropsForPayload) => {
          dispatch({ type: 'ADD_ITEM', payload })
     }
     const removeProduct = (payload: PropsForPayload) => {
          dispatch({ type: 'REMOVE_ITEM', payload })
     }
     const clearCart = () => {
          dispatch({ type: 'CLEAR' })
     }
     const handleCheckout = () => {
          console.log('CHECKOUT', state);
          dispatch({ type: 'CHECKOUT' })
     }
     const contextValues = {
          removeProduct,
          addProduct,
          increase,
          decrease,
          clearCart,
          handleCheckout,
          ...state
     }
     return (
          <CartContext.Provider value={contextValues} >
               { children}
          </CartContext.Provider>
     );
}
export default CartContextProvider;

到目前为止一切都很好,当我尝试使用cartcontext 的Provider 来调用AddToCart 方法时,出现错误。这是我打电话的方式:

<button
    onClick={() => addProduct(product)}
    className="btn btn-primary btn-sm">Add to cart</button>

上面 props 中的 product 是 ProductCONtext 类型 - IProduct 类型。这是我面临的错误:

src/pages/product/index.tsx:72:72
TS2345: Argument of type 'IProducts | undefined' is not assignable to parameter of type 'PropsForPayload'.
  Type 'undefined' is not assignable to type 'PropsForPayload'.

这个实现有什么问题? 我基本上是想复制这个:https://github.com/AlexSegen/react-shopping-cart/tree/master/src/contexts

0 个答案:

没有答案