我是 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;
我知道我需要在await之前使用const user = jsonApi.getUser();
但我們只能在async函式內部這樣做。
所以,我試圖這樣做: const UserPage = async () => { }
但我有一個錯誤:

uj5u.com熱心網友回復:
為了在反應中執行副作用,您應該考慮使用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資料尚不存在的情況,方法是不渲染任何內容(空值)或在兩者之間顯示一些加載狀態。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/322552.html
標籤:javascript 反应 异步 承诺 拿来
