【发布时间】:2019-11-20 14:35:29
【问题描述】:
我进行 API 调用。
似乎 React 继续构建一个没有数据的表,从而引发了
的错误Uncaught TypeError: Cannot read property 'map' of undefined
这就是我正在做的事情
useEffect() 很简单
const [data, setData] = useState();
const [isBusy, setBusy] = useState()
useEffect(() => {
setBusy(true);
async function fetchData() {
const url = `${
process.env.REACT_APP_API_BASE
}/api/v1/endpoint/`;
axios.get(url).then((response: any) => {
setBusy(false);
setData(response.data.results)
console.log(response.data.results);
});
}
fetchData();
}, [])
然后我尝试使用来自上述 API 调用的数据呈现一个表格(当它可用时)
<div className="col-md-12 mt-5">
{isBusy ? (
<Loader />
) : (
<table className="table table-hover">
<thead>
<tr>
<th scope="col">Pharmacy User Full Name</th>
<th scope="col">Tests This Month</th>
<th scope="col">Tests This Week</th>
<th scope="col">Last Test Date</th>
</tr>
</thead>
<tbody>
{data.map((item: any, index: any) => {
return (<tr>
<th scope="row" key={index}>{item.name}</th>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
</tr>
)
})}
</tbody>
</table>
)}
</div>
上面的内容对我来说足够直观。所以不确定我需要做什么。谢谢。
【问题讨论】:
-
你的 console.log 显示什么?
-
@Konstantin
Uncaught (in promise) TypeError: Cannot read property 'map' of undefined -
我认为@Vencovsky 解决方案应该适合您。请记住,您可能需要先使用
.json()解析收到的结果
标签: reactjs react-hooks