簡體   English   中英

React - 上下文提供者 - 調用異步 Function 內部消費者在 Promise 解決后什么都不返回

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

我正在嘗試從提供程序調用異步 function,然后根據響應顯示內容,但沒有返回任何內容。 有人可以告訴我我做錯了什么嗎? 下面是代碼:

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

我可以看到 getProfile 返回帶有配置文件數據的 promise,即使我刪除了profile &&也沒有顯示。 我以同樣的方式使用了其他功能。 getProfile 是唯一的異步 function 並且不知道為什么我會遇到這個問題。

有任何想法嗎? 謝謝

假設您的UserConsumer的渲染邏輯是這樣的:

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

由於您沒有在此 function 中返回任何內容:

     ({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 組件的返回部分執行異步操作。

如果需要基於服務器端數據(如配置文件數據)渲染一些 UI,則需要在useEffect中獲取數據,然后將接收到的數據放入state中,並使用state作為組件返回。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM