React:刷新页面时 API 调用失败
2021-10-05
2263
这是我的代码:
import Base from "./Base";
import axios from "axios";
import { createData } from "../../utils";
import { useState, useEffect } from "react";
export default function Today(props) {
const [scoops, setScoops] = useState(0);
//Fetch api/scoops/today
const fetchScoops = async () => {
const res = await axios.get("http://localhost:8000/api/scoops/today/");
setScoops(res.data);
};
useEffect(() => {
fetchScoops();
}, []);
console.log(scoops[0]);
const rows = [
createData(0, 1, scoops[0].title, "http://example.com"),
createData(1, 2, "Paul McCartney", "http://example.com"),
createData(2, 3, "Tom Scholz", "http://example.com"),
createData(3, 4, "Michael Jackson", "http://example.com"),
createData(4, 5, "Bruce Springsteen", "http://example.com"),
];
return <Base rows={rows} duration="Today" />;
}
这是控制台返回的内容:
> undefined
> Today.js:20 {url: 'http://localhost:8000/api/scoops/1/', title: 'Hello World!', rank: 0, created_at: '2021-10-05T04:44:52.027336Z', updated_at: '2021-10-05T04:44:52.027336Z'}
问题是当我刷新页面时,我收到以下错误消息:
TypeError: Cannot read properties of undefined (reading 'title')
非常感谢您的帮助!
更新 : 可选链接 解决了这个问题,效果很好。
scoops[0]?.title
3个回答
您可以将初始
scoops
状态设置为
[]
const [scoops, setScoops] = useState([]);
在使用
conditionalRendering
获取数据时呈现
scoops
return <> {scoops.lenght > 0 && <Base rows={rows} duration="Today" />} </>;
thepouria
2021-10-05
问题是,您正在将
scoops
初始化为
0
,但将其用作数组:
scoops[0]
尝试将
scoops
初始化为空数组。因此,类似这样的操作应该有效:
const [scoops, setScoops] = useState([]);
此外,当您执行此操作时:
scoops[0].title
,您应该改用
可选链接
并使用
scoops[0]?.title
Hassan Naqvi
2021-10-05
您应该使用 可选链接 (?.)
scoops?.[0]
Pedro L
2022-09-08