简体   繁体   English

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

[英]How to access nested JSON data | REACT

I have a problem when trying to fetch one nested JSON object from local API endpoint /user/{id} that looks like this:我在尝试从本地 API 端点/user/{id}获取一个嵌套的 JSON object 时遇到问题,如下所示:

{"userId":122,"name":"kissa","email":"kissa@kissa.com","phone":"04819283921","profile":{"profileId":1,"profileName":"student"}}

Everything else works like a charm but when trying to implement "user.profile.profileName" it gives me an error when reloading the page:其他一切都像一个魅力,但当试图实现“user.profile.profileName”时,它在重新加载页面时给我一个错误:

Uncaught TypeError: Cannot read properties of undefined (reading 'profileName')未捕获的类型错误:无法读取未定义的属性(读取“profileName”)

User.jsx用户.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;

Without {user.profile.profileName} property the table looks good and every other data is visible.如果没有{user.profile.profileName}属性,表格看起来不错,其他所有数据都可见。

I tried to fetch data from nested JSON object and excepted it to work like other properties but keys inside profile cant be fetched like other properties.我试图从嵌套的 JSON object 中获取数据,并排除它像其他属性一样工作,但不能像其他属性一样获取配置文件中的键。

At first render, your user is not loaded yet, so user.profile is undefined.第一次渲染时,你的用户还没有加载,所以user.profile是未定义的。

So you can either, have an early return while you do not have a user loaded因此,您可以在没有加载用户的情况下提前返回

const [user, setUser] = useState();
...

if (!user) return null;

Or use the optional chaining in your JSX或者在你的 JSX 中使用可选链

<td>{user?.profile?.profileName}</td>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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