在 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 但沒有任何效果...
謝謝。
uj5u.com熱心網友回復:
我認為你應該改變React.useEffect這個
React.useEffect(() => {
fetch("/data.json")
.then(response => response.json())
.then(data => {
setCustomers(data.customers) //this is where I made the change
});
}, []);
uj5u.com熱心網友回復:
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>
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/359692.html
標籤:javascript 数组 反应 json 目的
上一篇:讀取嵌套的JSON回傳NULL
