axios React:刷新页面时API调用失败

yvt65v4c  于 2022-11-05  发布在  iOS
关注(0)|答案(3)|浏览(212)

下面是我的代码:

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
exdqitrt

exdqitrt1#

可以将初始scoops状态设置为[]

const [scoops, setScoops] = useState([]);

使用conditionalRendering提取数据时渲染scoops

return <> {scoops.lenght > 0 && <Base rows={rows} duration="Today" />} </>;
tvz2xvvm

tvz2xvvm2#

问题是,您将scoops初始化为0,但却像使用数组一样使用它:scoops[0]
尝试将scoops初始化为一个空数组,这样就可以了:

const [scoops, setScoops] = useState([]);

此外,您在何处执行此操作:scoops[0].title您应该改用Optional chainingscoops[0]?.title

相关问题