【问题标题】:React not rendering data from fetch inside useEffectReact 不从 useEffect 中的 fetch 渲染数据
【发布时间】:2021-11-15 05:10:56
【问题描述】:

类似于question:但数据源自 fetch() 并且有一个嵌套的 .then 来获取数据对象 data.list_helado,它是一个字典列表。

为什么页面上不会呈现数据?

import React, { useEffect, useState } from "react";
import {Helados} from "../components/Helados";

function BiteroInfoPage() {

  // Initate array of helados (a data object of type dict) and their states
  const [helados, setHelados] = useState([]);

  // Fetch the list of helados initialized from database
  useEffect(() => {
  fetch("/list_initialized")
    .then((response) => response.json())
    .then((data) => {
      const updatedData = [...data.list_helado];
      setHelados(updatedData);
    });
}, []);

  return (
    <div className="biteroInfo">
      <h1>Bitero Segments</h1>
      <Helados prop={helados}/>
    </div>
  );
};

export default BiteroInfoPage;

Helados.js 在哪里:

import React from 'react';
import { List, Header} from "semantic-ui-react"

export const Helados = ({prop}) => {
console.log(prop)
console.log("Above returns: (4) [{…}, {…}, {…}, {…}]")
    return (
        <List>
            {prop.map((helado, index) => {
                return (
                    <List.Item key={index}>
                        <Header>{helado.study_name}</Header>
                    </List.Item>
                );
            })}
        </List>
    );
};

【问题讨论】:

  • 你确定updatedData 被填满了吗?
  • 我这么认为?当我在 const updatedData 下方放置一个 console.log(updatedData) 时,我得到的控制台输出为: (4) [{...}, {...}, {...}, {...}]

标签: javascript reactjs react-hooks fetch-api use-effect


【解决方案1】:

更新您的useEffect 使其看起来像这样。您没有正确处理response.json()。你不应该有任何嵌套调用。

useEffect(() => {
  fetch("/list_initialized")
    .then((response) => response.json())
    .then((data) => {
      const updatedData = [...data.list_helado];
      setHelados(updatedData);
    });
}, []);

【讨论】:

  • @k450 谢谢。不幸的是,这在显示数据的控制台中创建了一个无限循环的调用:(4) [{...}, {...}, {...}, {...}],但仍然没有实际呈现在屏幕上。
  • 是的,你不希望 helados 在 useEffect 依赖数组中。
  • 您能否在Helados 组件中console.log prop,并在您的问题中发布它包含的内容?
  • 我觉得自己很傻......在某个时候,我将 study_name 更改为 studyName。我会接受这个答案作为正确的解决方案,因为不正确的 response.json() 处理也有贡献。谢谢!
  • 没有问题。很高兴你明白了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-18
  • 2022-11-26
  • 2016-12-26
  • 2022-01-27
  • 2018-11-05
  • 2020-07-06
相关资源
最近更新 更多