【问题标题】:How to retrieve a fetch data from a JSON?如何从 JSON 中检索获取数据?
【发布时间】:2021-12-28 18:00:44
【问题描述】:

在 React 组件中

import React from 'react';
export default function Customers (props) {
   const [customers, setCustomers] = React.useState([]);
   React.useEffect(() => { 
      fetch("/data.json").then(response => response.json())
      .then(data => {
         setCustomers([data])
      })
   }, []);

   return (
      <div id='Customers'>
         {customers.map(c => c.name)}
      </div>
   )

如何仅显示公共目录中名为 data.json 的文件中的客户姓名?

{
    "customers": [
        {
            "id": 542,
            "name": "E"
        },
        {
            "id": 354,
            "name": "V"
        },
        {
            "id": 54534
            "name": "A"
        }        ,
        {
            "id": 33,
            "name": "K"
        }
    ],
    "packages": [
        {
            "id": 3643453453453,
            "weight": 6343
        },
        {
            "id": 453453,
            "weight": 4534534534
        }
    ]
}

我尝试使用 customers["customers"] 或 customers.customers 但没有任何效果...

谢谢。

【问题讨论】:

  • data.customers 而不是 [data]
  • 你为什么要把[data]传递给setCustomers()
  • 如果你做console.log(customers)你会得到什么?我也认为你应该像这样 setCustomers(data) 将数据传递给客户(不带 [ ])

标签: javascript arrays reactjs json object


【解决方案1】:
import React from 'react';
export default function Customers (props) {
   const [data, setData] = React.useState({});
   React.useEffect(() => { 
      fetch("/data.json").then(response => response.json())
      .then(res => {
         setCustomers(res)
      })
   }, []);

   return (
      <div id='Customers'>
         {data && data.customers ? data.customers.map(c => c.name) : null}
      </div>
   )

【讨论】:

    【解决方案2】:

    我觉得你应该把React.useEffect改成这个

    React.useEffect(() => { 
      fetch("/data.json")
      .then(response => response.json())
      .then(data => {
        setCustomers(data.customers) //this is where I made the change
      });
    }, []);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-16
      • 1970-01-01
      • 1970-01-01
      • 2020-03-08
      • 2021-07-17
      • 1970-01-01
      相关资源
      最近更新 更多