我试图从提供程序调用一个异步函数,然后根据响应显示内容,但没有返回任何内容。有人能告诉我我做错了什么吗?以下是代码:
const App = () => {
return (
<>
<Header />
<UserConsumer>
{
({getProfile}) => {
getProfile.then(profile) => {
return profile && (
<h3>{profile.name}</h3>
)
}
}
}
</UserConsumer>
</>
)
}
我可以看到getProfile返回了一个带有概要文件数据的promise,即使我删除了profile &&
,也不会显示任何内容。我以同样的方式使用了其他函数。getProfile是唯一的异步函数,不确定我为什么会出现这个问题。
有什么想法吗?感谢
假设UserConsumer
的呈现逻辑如下:
<div>{props.children({getProfile})}</div>
由于您在此函数中没有返回任何内容:
({getProfile}) => {
getProfile.then(profile) => {
return profile && ( // this is return value of then callback, not props.children
<h3>{profile.name}</h3>
)
}
}
每次React渲染UserConsumer
时,要渲染的最终JSX是:
<div>{undefined}</div>
代码的主要问题是,您不应该在React Components的返回部分执行异步操作。
如果您需要基于服务器端数据(如配置文件数据(呈现一些UI,则需要在useEffect
中提取数据,然后将接收到的数据放在一些state
中,并使用state
来返回组件。