下面是我的代码:
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')
我们非常感谢您的帮助!
更新:Optional chaining解决了这个问题,效果很好。
scoops[0]?.title
3条答案
按热度按时间exdqitrt1#
可以将初始
scoops
状态设置为[]
使用
conditionalRendering
提取数据时渲染scoops
tvz2xvvm2#
问题是,您将
scoops
初始化为0
,但却像使用数组一样使用它:scoops[0]
尝试将
scoops
初始化为一个空数组,这样就可以了:此外,您在何处执行此操作:
scoops[0].title
您应该改用Optional chaining和scoops[0]?.title
nnsrf1az3#
您应该使用Optional chaining (?.)