繁体   English   中英

Typescript 使用上下文反应

[英]Typescript UseContext React

我是 Typescript 的新手,在默认卡上做出反应并收到此错误

我正在尝试设置使用上下文并将其与使用 state 或使用 reducer 一起使用,但我无法为此进行初始设置

Error:
Argument of type '{ cartitem: { id: number; name: string; description: string; price: string; }; addCart: () => void; removeCart: () => void; }' is not assignable to parameter of type 'CartContextType'.
  Types of property 'cartitem' are incompatible.
    Type '{ id: number; name: string; description: string; price: string; }' is missing the following properties from type 'ICart[]': length, pop, push, concat, and 29 more.ts(2345)



import React, { createContext } from 'react';
export interface ICart {
    id: number;
    name: string;
    description: string;
    price: string;
  }

export type CartContextType = {
    cartitem: ICart[];
    addCart: (cart: ICart, totalAmount:number) => void;
    removeCart: (id: number) => void;
  };

  const defalutCart={cartitem:{
    id: 0,
    name: 'string',
    description: 'string',
    price: 'string'},
    addCart: () => {},
    removeCart: () => { }
  }

export const CartContext = createContext<CartContextType | null>(defalutCart);

您的变量defalutCart需要属性cartitem是一个数组。 通过正确的拼写和更改,这是您更新的代码:

const defaultCart = {
  cartitem: [
    {
      id: 0,
      name: "string",
      description: "string",
      price: "string",
    },
  ],
  addCart: () => {},
  removeCart: () => {},
};

你看到 object 现在是如何包装在数组中的了吗? 如果它解决了您的问题,请将其标记为正确。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM