如何管理来自 fetch promise 的数据?

How to manage with data from fetch promise?

我是 JS 和 React 的初学者。

我有一个问题:

import React from "react";

import JsonApi from "../../services/jsonApi";

const UserPage = () => {
  const jsonApi = new JsonApi(); //it is my class which has methods 
                                 //to manage with data(get,post,etc);

  const user = jsonApi.getUser(); //returns promise,but i need an object with data!
                                  //promise has such view:
                                  //[[Prototype]]: Promise
                                  //[[PromiseState]]: "fulfilled"
                                  //[[PromiseResult]]: Object  !!!!i need this data!!!!
  console.log(user); //Promise.

  /* i know that a i can do so:
     user.then((data) => console.log(data));

     but,using this way,i can only log!But i need an object with data!
  */


  return (
    <div className="app">
      <h1>{user.name}</h1> 
      <p>Here are info about users!</p>
    </div>
  );
};

export default UserPage;

我知道我需要在 const user = jsonApi.getUser();

之前使用 await

但我们只能在 async 函数中做到这一点。

所以,我尝试这样做:const UserPage = async () => { }

但我犯了一个错误:

为了在 React 中执行副作用,您应该考虑使用 useEffect hook. After the effect you need to store the data retrieved in react state by using the useState 钩子。最后您的代码如下所示:

import React, { useState, useEffect } from "react";
import JsonApi from "../../services/jsonApi";

const UserPage = () => {
  const [user, setUser] = useState(null);

  useEffect(() => {
    const jsonApi = new JsonApi();
    jsonApi.getUser().then((user) => {
      setUser(user);
    });
  }, []);

  if (!user) return null;
  return (
    <div className="app">
      <h1>{user.name}</h1>
      <p>Here are info about users!</p>
    </div>
  );
};

export default UserPage;

请记住,在异步 getUser 解析之前,用户不会被填充,因此您必须处理 user 数据尚未存在的情况,要么不呈现任何内容(null)或者通过在两者之间显示一些加载状态。