【问题标题】:React show data from array of objects反应显示来自对象数组的数据
【发布时间】:2021-09-28 18:59:16
【问题描述】:

今天我做了一个 useFetch 钩子来获取某个类别的所有数据。正如您在图像上看到的,可以看到 JSON 格式的所有数据。您还可以看到它位于对象数组中。我想知道如何在页面上以正常格式显示这些数据。大多数时候我收到 data.name NULL 的错误。但正如您所见,图像上的数据以 JSON 格式正确获取。我只是不明白如何正常显示所有这些数据。有什么建议吗?

enter image description here

enter image description here

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


【解决方案1】:

这可能对你有帮助

...

const Product = () => {

    const { id } = useParams();
    const { data, error, isPending } = useFetch("http://localhost:8080/products/category/" + id);

        return (
            { data && data.length &&
                data.map((row) =>{
                  <p>row.name</p>
                })
            }
        )
}

...

【讨论】:

    【解决方案2】:

    你的 useFetch 是异步的,我可以看到 isPending 变量,你为什么不使用它?

    const { id } = useParams();
    const { data, error, isPending } = useFetch("http://localhost:8080/products/category/" + id);
    
    
        return (
            <p>{isPending ? null : JSON.stringify(data)}</p>
        )
    

    【讨论】:

      猜你喜欢
      • 2021-03-17
      • 1970-01-01
      • 1970-01-01
      • 2021-02-07
      • 2021-11-09
      • 2018-02-18
      • 1970-01-01
      • 2017-11-26
      • 2019-05-06
      相关资源
      最近更新 更多