如何访问 JSON 嵌套 obj 以在 React JSX 中设置状态和显示?

How can I access JSON nested obj to set state and display in React JSX?

提问人:Samara 提问时间:9/5/2023 最后编辑:Samara 更新时间:9/5/2023 访问量:41

问:

我正在从我的 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')
JavaScript ReactJS JSON 对象 嵌套

评论

1赞 pilchard 9/5/2023
正如答案中所指出的,您在这里使用逗号运算符很奇怪,但实际上也不是您想要的,您想专门设置它,因为如果更改并且状态已经为 true,它会将其更改为 false。此外,当您知道稍后将状态设置为对象时,将状态初始化为数组是没有意义的,要么将其设置为空对象,要么启动。setIsLoaded(!isLoaded)trueidnull
0赞 Raiyad Raad 9/5/2023
您是否获得了该州内部的确切数据?我能够正确地呈现信息。请检查这个: playcode.io/1583892customer

答:

0赞 Raed 9/5/2023 #1

如果在同一函数中触发状态更新,React 将“批量”更新。基本上,你需要更新你的代码,以便 react 知道调用并需要同时发生。setCustomersetIsLoaded

您可以在 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答案已更新