繁体   English   中英

如何访问嵌套的 JSON 数据 | 反应

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM