我想用 typescript 写上下文。这里的API是通过axios绘制的,然后用卡片写在屏幕上。但是它给出了一个关于上下文类型的错误,我如何消除它?
我的错误是:键入“{ data:产品列表|undefined; setData:React.Dispatch<React.SetStateAction<ProductList| undefined>>“}”不能分配给类型“productType[]”。对象文本只能指定已知属性,并且类型“productType[]”中不存在“data”。
import axios from "axios";
import { createContext, useEffect, useState } from "react";
interface ContextChildrenProps {
children: JSX.Element
}
export interface SingleProduct {
title: string,
description: string,
thumbnail: string
}
export interface productType {
product: SingleProduct
}
export interface ProductList {
data: productType[]
}
export const GlobalProductsContext = createContext<productType[] | null>({} as productType[])
export const ProductsContextProvider = ({ children }: ContextChildrenProps) => {
const [data, setData] = useState<ProductList>()
useEffect(() => {
axios.get('https://fakestoreapi.com/products')
.then(res => {
console.log(res)
setData(res.data)
})
}, [])
return (
<GlobalProductsContext.Provider value={{ data, setData }}>
{children}
</GlobalProductsContext.Provider>
)
}
import React from 'react'
import { productType } from '../context/GlobalData'
const SingleCard = ({ product }: productType) => {
return (
<>
<div className="col-lg-4 p-2" data-aos="flip-left">
<div className="card" style={{ width: '100%', height: '100%' }}>
<img src={product.thumbnail} className="card-img-top" alt="..." />
<div className="card-body">
<h5 className="card-title">{product.title}</h5>
<p className="card-text">{product.description}</p>
<a href="#" className="btn btn-primary">Go somewhere</a>
</div>
</div>
</div>
</>
)
}
export default SingleCard
1条答案
按热度按时间zsohkypk1#
上下文值的TS类型不正确。
尝试: