【发布时间】:2021-12-04 06:40:12
【问题描述】:
我是 typescript 和 React 的新手。该项目的想法是从我创建的 JSon 文件中捕获一些信息(背面)并将它们显示在卡片上(正面)。我已经设法获得这些信息并将它们显示在一个数组中,现在的目标是用 reactJs 把它放在表格中。但我有以下错误:
TS2322:键入“AppState | undefined' 不能分配给类型 'ICards |不明确的'。 “AppState”类型缺少“ICards”类型的以下属性:title、items、urlSuffixe Cards.tsx(8, 3):预期类型来自属性“cards”,该属性在“IntrinsicAttributes & CardsProps”类型上声明。
出了什么问题?
卡片.tsx:
import React, { FC, useState } from "react";
import ListCard from "../ListCard/ListCard";
import { getCards } from "../../api/index";
import { ICardItems, ICards } from "../../decl";
import "./Cards.css";
export interface CardsProps {
cards: ICards | undefined;
}
const Cards = ({ cards }: CardsProps) => {
return (
<section className="section cards">
<div className="cards__wrap container">
<div className="section__title">
<h1>{cards?.title}</h1>
</div>
{cards?.items.map((card: any) => {
<ListCard key={card.id} {...card} />;
})}
{/*<div className="cards__list">*/}
{/* <div className="cards_list_container">*/}
{/* <ListCard />*/}
{/* <ListCard />*/}
{/* <ListCard />*/}
{/* <ListCard />*/}
{/* <ListCard />*/}
{/* <ListCard />*/}
{/* <ListCard />*/}
{/* <ListCard />*/}
{/* <ListCard />*/}
{/* <ListCard />*/}
{/* </div>*/}
{/*</div>*/}
</div>
</section>
);
};
export default Cards;
Home.tsx:
import React, { useState, useEffect } from "react";
import axios from "axios";
import Cards from "../Cards/Cards";
import { ICardItems, ICards } from "../../decl";
import { getCards } from "../../api";
import "./Home.css";
interface AppState {
cards: ICards | undefined;
}
const Home = () => {
const [appCards, setAppCards] = useState<AppState>();
const fetchCards = async () => {
const cardsPages = await getCards();
setAppCards({ cards: cardsPages });
};
console.log(appCards);
useEffect(() => {
fetchCards();
}, []);
return (
<div className="home">
<Cards cards={appCards} />
</div>
);
};
export default Home;
cards.decl.ts:
export type ICards = {
title: string;
items: ICardItems;
urlSuffixe: string;
};
export type ICardItem = {
id: number;
img: string;
gender: string;
name: string;
};
export type ICardItems = ICardItem[];
【问题讨论】:
-
getCards() 中的 axios 请求是否输入正确? fetchCards 中的cardPages 变量是ICards 类型的吗?
标签: javascript reactjs typescript