【发布时间】: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