Gri*_*420 2 typescript reactjs
我有这个 React/Typescript 页面:
import React, { useState, useEffect } from 'react';
import { Page } from './Page';
import { PageTitle } from './PageTitle';
import { Button, Card } from 'react-bootstrap';
function PlayersPage() {
const [isLoading, setIsLoading] = useState(false);
const [playersData, setPlayersData] = useState([]);
//Fetch all players from database
useEffect(() => {
//setIsLoading(true);
fetch('http://localhost:44326/api/Players')
.then((response) => {
if (response.ok) {
return response.json();
}
})
.then((data) => setPlayersData(data));
//.then(setIsLoading(false));
}, []);
return (
<Page>
<div style={{ padding: 20 }}>
<PageTitle>Toons</PageTitle>
</div>
<div>
{playersData.map((data) => (
<div key={data.ID}>
<Card>
<Card.Title>{data.ID}</Card.Title>
<Card.Text>{data.Handle}</Card.Text>
<Card.Body>
<div className="lables">
<Card.Text>Role</Card.Text>
</div>
<div className="lables">
<Card.Text>{data.Role}</Card.Text>
</div>
<Button variant="primary">Work</Button>
</Card.Body>
</Card>
<br></br>
</div>
))}
</div>
</Page>
);
}
export default PlayersPage;
Run Code Online (Sandbox Code Playgroud)
我收到此错误:在包含或 的Property 'ID' does not exist on type 'never'.ts(2339)每一行上。data.IDdata.whatever
为什么这些值永远不会被使用或始终为空?我在其他几个应用程序中使用几乎相同的代码,因此我不确定这种情况有什么不同。提前致谢。
playersData您需要在贴花时添加类型。
interface DataType {
ID: string;
Handle: string;
Role: string;
}
const [playersData, setPlayersData] = useState<Array<DataType>>([]);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2041 次 |
| 最近记录: |