React Typescript .map不是类型化数组上的函数错误


import React, { useState, useEffect } from "react"
import axios from 'axios'
import postImage from "assets/post_image.png"
import styled from "styled-components"
type TrendingPostsProps = {};
const TrendingPostsContainer = styled.div``;
const SinglePostContainer = styled.div``;
const TrendingPostImage = styled.img``;
const TrendingPostTitleContainer = styled.div``;
export const TrendingPosts: React.FC<TrendingPostsProps> = () => {
interface News {
news_id: number;
title: string;
datetime: string;
summary: string;
details: string;
image: string;
hit: number;
}

const [newsData, setNewsData] = useState<News[]>([]);
useEffect(() => {

const getNewsData = async () => {
const response = await axios.get<News[]>("http://localhost:5000/news")
setNewsData(response.data)
}
getNewsData()
}, [])
console.log(typeof newsData)
console.log(newsData)
return (
<>
<TrendingPostsContainer>
<h2>Trending Posts</h2>
{
<ul>
{newsData.map((item, index) => (
<li key={index}>
<SinglePostContainer>
<TrendingPostImage src={postImage} alt=""></TrendingPostImage>
<TrendingPostTitleContainer>
<h3>{item.title}</h3>
{/* <p>{item.date}</p> */}
</TrendingPostTitleContainer>
</SinglePostContainer>
</li>
))}
</ul>
}
</TrendingPostsContainer>
</>
);
};

嗨,我试图从现有的后端与React Typescript获取数据。当我悬停(VSCode)上的响应。在useEffect函数中,它表示数据的类型为News[]。但是,当我尝试映射它时,它会在标题中抛出错误,如果我像代码片段中那样打印newsData及其类型,它也会打印这一点。所以我认为我应该能够迭代这些数据newsData.data.map但是当我这样做的时候,它显示的是Property 'data' does not exist on type 'News[]'。我真的很困惑,数据应该是一个数组,我怎么迭代它?

提前感谢。

您声明newsData具有数组类型,但您使用对象setNewsData。你需要更新setNewsData的参数,它是一个数组。

const getNewsData = async () => {
const response = await axios.get<{data: News[]>}("http://localhost:5000/news");
setNewsData(response.data.data);
};

尝试:

import type { AxiosResponse } from ‘axios’;
const response = await axios.get<AxiosResponse<News[]>>("http://localhost:5000/news") 
setNewsData(response.data)

相关内容

  • 没有找到相关文章