简体   繁体   English

从 api 获取数据后在 React 中显示嵌套对象?

[英]Displaying Nested Objects in React after fetching the data from an api?

The user data from json placeholder has the address as an object inside of the user object and I am trying to figure out how to display that data for learning and understanding purposes来自 json 占位符的用户数据将地址作为用户对象内部的对象,我试图弄清楚如何显示该数据以用于学习和理解目的

import React, { useState, useEffect } from "react";
import "./App.css";

const App = () => {
  const [users, setUsers] = useState([]);
  const [user, setUser] = useState({});
  useEffect(() => {
    getUsers();
    getUser();
    //eslint-disable-next-line
  }, []);

  const getUsers = async () => {
    const res = await fetch("https://jsonplaceholder.typicode.com/users");
    const data = await res.json();
    setUsers(data);
  };

  const getUser = async () => {
    const res = await fetch("https://jsonplaceholder.typicode.com/users/1");
    const data = await res.json();
    setUser(data);
    console.log(data);
  };

  return (
    <div className="App">
      <h3 style={{ marginBottom: "5px" }}>
        Getting an Array of users from an Api
      </h3>
      <ul>
        {users.map(user => (
          <li style={{ marginBottom: "5px", paddingLeft: "10px" }}>
            Name:{user.name} <br />
            Email:{user.email}
          </li>
        ))}
      </ul>
      <div className="card" style={{ width: "400px" }}>
        <h3>Name: {user.name}</h3>
        <p>Email: {user.email}</p>

      </div>
    </div>
  );
};

export default App;

to this point everything works just fine到目前为止一切正常

when I try to access the user address it throws an error当我尝试访问用户地址时,它会引发错误

<div className="card" style={{ width: "400px" }}>
        <h3>Name: {user.name}</h3>
        <p>Email: {user.email}</p>
        <p>Address: {user.address.street}
      </div>

How do I access and object within an object?如何访问和对象内的对象?

You have to set init user.您必须设置 init 用户。
Because of rendering null issue.因为渲染空问题。

const defaultUser = {
    name: "",
    email: "",
    address: {
        street: ""
    }
};

const [users, setUsers] = useState([defaultUser]);
const [user, setUser] = useState(defaultUser);

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

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