React 无法在 useEffect 中渲染来自 fetch 的数据
2021-09-21
79
与此 问题 类似:但数据源自 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>
);
};
1个回答
更新您的
useEffect
,使其看起来像这样。您没有正确处理
response.json()
。您不应该有任何嵌套调用。
useEffect(() => {
fetch("/list_initialized")
.then((response) => response.json())
.then((data) => {
const updatedData = [...data.list_helado];
setHelados(updatedData);
});
}, []);
Dan Zuzevich
2021-09-21