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

时间:2019-12-30 17:05:53

标签: javascript json reactjs object

来自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;

到目前为止,一切正常

当我尝试访问用户地址时会抛出错误

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

如何访问对象中的对象?

1 个答案:

答案 0 :(得分:2)

您必须设置初始化用户。
由于呈现null问题。

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

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