提问人:Samara 提问时间:9/5/2023 最后编辑:Samara 更新时间:9/5/2023 访问量:41
如何访问 JSON 嵌套 obj 以在 React JSX 中设置状态和显示?
How can I access JSON nested obj to set state and display in React JSX?
问:
我正在从我的 REST API @“localhost:3001/customers/id” 获取一个 JSON 对象并尝试将其设置为状态,但是在尝试在 JSX 中显示内容时,我无法访问我的嵌套对象。
import { React, useState, useEffect } from "react";
import { useParams } from "react-router-dom";
import './CustomerItem.css'
const CustomerItem = () => {
const { id } = useParams()
const [customer, setCustomer] = useState([])
const [isLoaded, setIsLoaded] = useState(false)
useEffect(() => {
fetch(`http://localhost:3001/customers/${id}`)
.then((response) => response.json())
.then((data) =>
setCustomer(data),
setIsLoaded(!isLoaded)
)
}, [id])
if (!isLoaded) return <h1>Please refresh...</h1>
return (
<div>
<h1> {customer.customerInfo.name} </h1>
<h3> {customer.vehicleInfo.year} {customer.vehicleInfo.make} {customer.vehicleInfo.model} </h3>
</div>
)
}
export default CustomerItem
{
"id": 1,
"customerInfo": {
"name": "Samara Grant",
"phone": "347-555-5555",
"email": "[email protected]",
"address": "123 Spring St New York, NY 11001"
},
"vehicleInfo": {
"year": "2018",
"make": "BMW",
"model": "M4",
"mileage": "18,564",
"vin": "WBS3R9C50FK331665",
"plateNumber": "M4DEULK"
},
"repairOrders": [
{
"id": 100,
"dateOfService": "03/12/2023",
"customerConcern": "Customer states intermittent whistling sound coming from bonnet. Only after vehicle is warm and @ idle",
"technicianDiagnosis": "Upon test drive audible whistling noise persists. Located @ PVC Valve in valve cover. Valve cover needs to be replaced",
"partsOrdered": "Qty: 1x - Part#11127846359 | S55 Valve Cover",
"serviceAdvisor": "JL",
"technician": "06"
},
{
"id": 101,
"dateOfService": "03/29/2023",
"customerConcern": "Customer states oil leak coming from engine",
"technicianDiagnosis": "Upon inspection oil leaking from valve cover. Valve cover appears to be unwarped. Gasket will need replacing.",
"partsOrdered": "Qty: 1x - Part#11127587804 | S55 Valve Cover Gasket Seal",
"serviceAdvisor": "JL",
"technician": "06"
}
]
}
当我控制台.log(data)时,我能够看到整个对象及其嵌套的对象信息。当我尝试在 JSX 中映射对象以访问嵌套数据时,它不允许它,因为它不是数组。使用如下所示的字符串文字给我
TypeError: Cannot read properties of undefined (reading 'year')
答:
0赞
Raed
9/5/2023
#1
如果在同一函数中触发状态更新,React 将“批量”更新。基本上,你需要更新你的代码,以便 react 知道调用并需要同时发生。setCustomer
setIsLoaded
您可以在 React 文档中找到更多详细信息: https://react.dev/learn/queueing-a-series-of-state-updates
尝试替换 :
.then((data) =>
setCustomer(data),
setIsLoaded(!isLoaded)
)
跟:
.then((data) => {
setCustomer(data);
setIsLoaded(!isLoaded);
})
评论
1赞
pilchard
9/5/2023
仅代码的答案是不受欢迎的。解释为什么这可能有助于解决 OP 的问题。
0赞
Raed
9/5/2023
@pilchard答案已更新
上一个:状态对象值不会更新
下一个:在 REACT 中访问对象列表
评论
setIsLoaded(!isLoaded)
true
id
null
customer