【发布时间】: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 () => { }
但我错了:
【问题讨论】:
-
一个 React 组件不能是一个
async函数,因为一个元素的承诺本身并不是一个有效的元素。您也可能不想在每次组件呈现时都发出请求 - 查看useEffect。
标签: javascript reactjs asynchronous promise fetch