簡體   English   中英

如何從 JSON 檢索獲取數據?

[英]How to retrieve a fetch data from a JSON?

在 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 但沒有任何效果...

謝謝。

我認為您應該將React.useEffect更改為此

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM