【问题标题】:How to manage with data from fetch promise?如何管理来自 fetch promise 的数据?
【发布时间】:2021-12-05 16:36:15
【问题描述】:

我是 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 () =&gt; { }

但我错了:

【问题讨论】:

  • 一个 React 组件不能是一个 async 函数,因为一个元素的承诺本身并不是一个有效的元素。您也可能不想在每次组件呈现时都发出请求 - 查看useEffect

标签: javascript reactjs asynchronous promise fetch


【解决方案1】:

为了在 react 中执行副作用,您应该考虑使用 useEffect 钩子。在效果之后,您需要使用 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)或显示一些加载状态介于两者之间。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-10
    • 1970-01-01
    • 1970-01-01
    • 2021-10-24
    • 2018-08-27
    • 2018-08-11
    • 2016-11-17
    • 2021-11-17
    相关资源
    最近更新 更多