【发布时间】:2021-09-28 18:59:16
【问题描述】:
今天我做了一个 useFetch 钩子来获取某个类别的所有数据。正如您在图像上看到的,可以看到 JSON 格式的所有数据。您还可以看到它位于对象数组中。我想知道如何在页面上以正常格式显示这些数据。大多数时候我收到 data.name NULL 的错误。但正如您所见,图像上的数据以 JSON 格式正确获取。我只是不明白如何正常显示所有这些数据。有什么建议吗?
import React from "react";
import "../Style/menu.css";
import { useParams, withRouter } from "react-router-dom";
import useFetch from "../ApiService/useFetch";
import { render } from "@testing-library/react";
const Product = () => {
const { id } = useParams();
const { data, error, isPending } = useFetch("http://localhost:8080/products/category/" + id);
return (
<p>{JSON.stringify(data)}</p>
)
}
export default Product;
import { useState, useEffect } from "react";
const useFetch = (url) => {
const [data, setData] = useState(null);
const [isLoading, setIsPending] = useState(true);
const [error, setError ] = useState(null);
useEffect(() => {
fetch(url) //custom url so you can reuse it
.then(res => {
if(!res.ok) {
throw Error('could not fetch data');
}
return res.json();
})
.then(data => {
setData(data);
setIsPending(false)
setError(null)
})
.catch(err => {
setError(null)
setIsPending(false)
})
}, [url]);
return {data, isLoading, error} //use properties with custom hook
}
export default useFetch;
【问题讨论】:
-
在
useFetch中的return之前添加console.log(data)并查看控制台上显示的内容 -
它给了我一个我需要显示的所有对象的数组!我还添加了图片
-
你是说你不知道如何在 HTML 中呈现它?有docs with examples。
-
如果不将
data传递给JSON.stringify,输出是什么?可能您将获得常规数组,因此map可以在该数组上并以您想要的任何方式呈现。 -
this : Uncaught Error: Objects are not valid as a React child (found: object with keys {id, name, description, allergies, price})。如果您打算渲染一组子项,请改用数组。
标签: javascript reactjs api frontend