React获取已完成承诺的值



我的子组件收到一个已完成的Promise,现在我想像这样访问它的值:

return (
<>
<h1>{profile.Email}</h1>
</>
)

在控制台console.log(profile)

中解析如下
Promise {<fulfilled>: {…}
[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Object
Email: "XXXXn@gmail.com"
Firma: "Dr"
Hausnummer: "1"
Land: "Deutschland"
LogoId: "Bildschirmfoto 2022-05-16 um 15.26.25.png"
Nachname: "BXXXX"
PLZ: "31840"
Stadt: "Hameln"
Strasse: "Gutsstr"
Telefon: "2121212121"
Titel: "Dr"
Typ: "XXXXX"
Vorname: "XXXX"
__typename: "Profil"

我想在return()中访问这些值中的每一个。我怎么做呢?我可以用

访问它们
profile.then((values) => {
email = values.Email
console.log(email)
})

在控制台中给出正确的值,但我需要返回值。有人能给我指个方向吗?

有多种方法可以解决这个问题,其中一种方法是在promise被解析时使用状态来存储值。要做到这一点,可以在解析响应或承诺时使用加载器。

const { profile } = props; //I'm pretending that profile comes as props
// if profile comes from an api that you're calling in the component itself, then initialize to a value and then set it
const [profileData, setProfileData] = useState();
useEffect(() => {
setProfileData(profile);
}, [profile])
return (
profileData ? 
<>{profileData.Email}</> :
<>loading...</>
);

如果这对你没有帮助,或者我的建议不是你想要的,请评论这个答案

我建议使用useStateuseEffect查看反应stateeffect钩子。

您可以使组件异步(不确定这是否是坏做法,但我这样做没有问题),但我建议只是使用useEffect和then()方法,在解决时设置状态。例如:

import { useState, useEffect } from "react";
function myComponent() {
const [profile, setProfile] = useState();

useEffect(() => {
<your async api call>.then((prof) => setProfile(prof));
}, []);
return (
data 
? <h1>{JSON.stringify(profile.Email)}</h1>
: <h1>Fetching Data...</h1>
)
}
export default myComponent;

最新更新