从 React.js 到 React.tsx 属性 'id' 的转换在类型 'never' 上不存在。 TS2339
Converting from React.js to React.tsx Property 'id' does not exist on type 'never'. TS2339
我正在尝试按照教程学习在类型脚本中做出反应。但是,当我构建解决方案时,我遇到了错误。
代码
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const DataFetching = () => {
const [posts, setPosts] = useState([]);
useEffect(() => {
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(res => {
console.log(res)
setPosts(res.data)
})
.catch(err => {
console.log(err)
})
})
return (
<div>
<ul>
{posts.map(post => (<li key={post.id}>{post.title}</li>))}
</ul>
</div>
);
};
export default DataFetching;
我遇到的错误
TypeScript error in src/DataFetching.tsx(21,43):
Property 'id' does not exist on type 'never'. TS2339
我正在学习以下教程 https://www.youtube.com/watch?v=bYFYF2GnMy8。感谢任何帮助或指导
您应该明确地将类型添加到 useState
。当您提供空数组打字稿时,推断其类型为 never[]
.
const [posts, setPosts] = useState<Post>([]);
您应该始终指定状态变量的 type
。在这种情况下,您使用的是 Post 数组。所以你必须创建一个 Post 接口并在 useState
.
中使用该类型
import React, { useState, useEffect } from 'react';
import axios from 'axios';
interface Post {
id: number;
title: string;
}
const DataFetching = () => {
const [posts, setPosts] = useState<Post[]>([]);
useEffect(() => {
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(res => {
console.log(res)
setPosts(res.data)
})
.catch(err => {
console.log(err)
})
})
return (
<div>
<ul>
{posts.map(post => (<li key={post.id}>{post.title}</li>))}
</ul>
</div>
);
};
export default DataFetching;
我正在尝试按照教程学习在类型脚本中做出反应。但是,当我构建解决方案时,我遇到了错误。 代码
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const DataFetching = () => {
const [posts, setPosts] = useState([]);
useEffect(() => {
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(res => {
console.log(res)
setPosts(res.data)
})
.catch(err => {
console.log(err)
})
})
return (
<div>
<ul>
{posts.map(post => (<li key={post.id}>{post.title}</li>))}
</ul>
</div>
);
};
export default DataFetching;
我遇到的错误
TypeScript error in src/DataFetching.tsx(21,43):
Property 'id' does not exist on type 'never'. TS2339
我正在学习以下教程 https://www.youtube.com/watch?v=bYFYF2GnMy8。感谢任何帮助或指导
您应该明确地将类型添加到 useState
。当您提供空数组打字稿时,推断其类型为 never[]
.
const [posts, setPosts] = useState<Post>([]);
您应该始终指定状态变量的 type
。在这种情况下,您使用的是 Post 数组。所以你必须创建一个 Post 接口并在 useState
.
import React, { useState, useEffect } from 'react';
import axios from 'axios';
interface Post {
id: number;
title: string;
}
const DataFetching = () => {
const [posts, setPosts] = useState<Post[]>([]);
useEffect(() => {
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(res => {
console.log(res)
setPosts(res.data)
})
.catch(err => {
console.log(err)
})
})
return (
<div>
<ul>
{posts.map(post => (<li key={post.id}>{post.title}</li>))}
</ul>
</div>
);
};
export default DataFetching;