簡體   English   中英

React Hooks:在上下文 API 中存儲的值發生更改后渲染組件?

[英]React Hooks: Render component after the value stored in context API has changed?

我正在 React 中開發一個 web 應用程序。 我正在嘗試執行以下操作:

  1. 從數據庫中獲取用戶信息並使用上下文 API 將其存儲。

  2. 當上下文改變時渲染組件。

問題是更新上下文顯然存在時間滯后,因此組件不會重新渲染。 如何確保組件在上下文值更新后重新渲染?

以下是我正在使用的代碼:

 const User = () => {    
     const {userinfo, setuserinfo} = useContext(Userinfo) //Declare useContext hooks
     useEffect(()=>{
         /*
          Compute the value of mid
         */         
         setuserinfo(mid);  //Set 'userinfo' using context API
     },[])

     return (
         <>
         {userinfo.map(ui =>
          //JSX to map userinfo to UI components
         )}
         </>
     )
}

提前非常感謝!

您可以在嘗試將其userinfo以呈現組件之前檢查或驗證用戶信息。

例如

// or use lodash.isNil, or lodash.isEmpty, or whatever check you want
const isNil = o => o === null || o === undefined; 

return ( isNil(userInfo) ?
  <span>Loading...</span> :
  <>
    {userinfo.map(ui =>
      //JSX to map userinfo to UI components
    )}
  </>
);

你可以嘗試這樣的事情。

return  userinfo && Array.isArray(userinfo) && userinfo.length ? (
         <>
         {userinfo.map(ui =>
          //JSX to map userinfo to UI components
         )}
         </>
       ) : <span>Loading... (or whatever)</span>;

暫無
暫無

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

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