简体   繁体   English

React - 上下文提供者 - 调用异步 Function 内部消费者在 Promise 解决后什么都不返回

[英]React - Context Provider - Calling Async Function Inside Consumer Returns Nothing After Promise is resolved

I'm trying to call an async function from the provider and then show content based on the response but nothing is returned.我正在尝试从提供程序调用异步 function,然后根据响应显示内容,但没有返回任何内容。 Can someone please advise what am I doing wrong?有人可以告诉我我做错了什么吗? Below is the code:下面是代码:

const App = () => {
  return (
    <>
      <Header />
      <UserConsumer>
        {
          ({getProfile}) => {
            getProfile.then(profile) => {
              return profile && (
                <h3>{profile.name}</h3>
              )
            }
          }
        }
      </UserConsumer>
    </>
  )
}

I can see getProfile returns a promise with profile data and even if I remove profile && nothing shows.我可以看到 getProfile 返回带有配置文件数据的 promise,即使我删除了profile &&也没有显示。 I have used other functions the same way.我以同样的方式使用了其他功能。 getProfile is the only async function and not sure why am I having this issue. getProfile 是唯一的异步 function 并且不知道为什么我会遇到这个问题。

Any ideas?有任何想法吗? Thanks谢谢

Suppose your UserConsumer 's rendering logic is something like this:假设您的UserConsumer的渲染逻辑是这样的:

<div>{props.children({getProfile})}</div>

Since you are not returning anything in this function:由于您没有在此 function 中返回任何内容:

     ({getProfile}) => {
        getProfile.then(profile) => {
          return profile && ( // this is return value of then callback, not props.children
            <h3>{profile.name}</h3>
          )
        }
      }

Everytime React renders UserConsumer , the final JSX to be rendered is this:每次 React 渲染UserConsumer时,最终要渲染的 JSX 是这样的:

    <div>{undefined}</div>

The main problem of your code, You are not supposed to do asynchronous operations in return sections of React Components.您的代码的主要问题是,您不应该在 React 组件的返回部分执行异步操作。

If you need to render some UI based on server side data (like profile data), you need to fetch data in useEffect , then put the received data in some state , and use the state in return of the component.如果需要基于服务器端数据(如配置文件数据)渲染一些 UI,则需要在useEffect中获取数据,然后将接收到的数据放入state中,并使用state作为组件返回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM