[英]How to access nested JSON data | REACT
我在嘗試從本地 API 端點/user/{id}獲取一個嵌套的 JSON object 時遇到問題,如下所示:
{"userId":122,"name":"kissa","email":"kissa@kissa.com","phone":"04819283921","profile":{"profileId":1,"profileName":"student"}}
其他一切都像一個魅力,但當試圖實現“user.profile.profileName”時,它在重新加載頁面時給我一個錯誤:
未捕獲的類型錯誤:無法讀取未定義的屬性(讀取“profileName”)
用戶.jsx
import React from "react";
import { useState, useEffect } from "react";
import { useParams } from "react-router-dom";
import './user.css';
const User = () => {
const [user, setUser] = useState([]);
const params = useParams();
useEffect(() => {
fetch("http://localhost:8080/api/users/" + params.id)
.then((response) => response.json())
.then((user) => setUser(user));
}, []);
return (
<div className="user__container">
<div className="user__table">
<table>
<thead>
<tr>
<th>UserId</th>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th>Profile</th>
</tr>
</thead>
<tbody>
<tr>
<td>{user.userId}</td>
<td>{user.name}</td>
<td>{user.email}</td>
<td>{user.phone}</td>
<td>{user.profile.profileName}</td>
</tr>
</tbody>
</table>
</div>
</div>
);
};
export default User;
如果沒有{user.profile.profileName}屬性,表格看起來不錯,其他所有數據都可見。
我試圖從嵌套的 JSON object 中獲取數據,並排除它像其他屬性一樣工作,但不能像其他屬性一樣獲取配置文件中的鍵。
第一次渲染時,你的用戶還沒有加載,所以user.profile
是未定義的。
因此,您可以在沒有加載用戶的情況下提前返回
const [user, setUser] = useState();
...
if (!user) return null;
或者在你的 JSX 中使用可選鏈
<td>{user?.profile?.profileName}</td>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.