React/React Context API:使用 useEffect() 钩子时等待上下文值 [英] React/React Context API: Wait for context values when using useEffect() hook

查看:50
本文介绍了React/React Context API:使用 useEffect() 钩子时等待上下文值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 React 开发一个网络应用程序,这是我想要做的:

I am developing a web app using React and here is what I am trying to do:

  1. 在最高阶组件中,检查用户是否已登录,如果已登录,则更新userinfo"上下文值.
  2. 在 Profile.js 中,获取userinfo"上下文值.
  3. 检查'userinfo'是否为空,并相应调用不同的API.

我写了下面的代码.问题是将 userinfo 上下文值传递给组件显然存在时间延迟.因此,当使用 useEffect() 钩子时,当 userinfo 不为 null 时,Profile.js 将呈现两次.

I wrote the below code. The problem is that there is apparently a time lag for the userinfo context value to be delivered to the component. So when using useEffect() hook, Profile.js will render twice when userinfo is not null.

有没有办法修复此代码,使其等待userinfo"变量,然后相应地调用相关 API,而不是之前?

Is there a way to fix this code so that it waits for 'userinfo' variable, and then call relevant APIs accordingly, not before?

下面是代码.有什么建议吗?提前非常感谢!

Below is the code. Any advice? Thanks a lot in advance!

import React, {useEffect, useContext} from 'react';
import Userinfo from "../context/Userinfo";


function Profile(props) {

   const {userinfo, setuserinfo}=useContext(Userinfo);

   useEffect(()=>{      
       ((userinfo==null)?
       /*API call A (When user is not logged in) */ :
       /*API call B (When user is logged in) */
       )},[userinfo])  

   return (
       (userinfo==null)?
       /*Elements to render when user is not logged in) */ :
       /*Elements to render when user is  logged in) */
   );
}

export default Profile;

推荐答案

这里最好的解决方案是在上下文提供程序中添加加载状态,一旦值更新,该状态就会重置.

The best solution here is to add a loading state in the context provider which is reset once the value is updated.

function Profile(props) {

   const {userinfo, loading, setuserinfo}=useContext(Userinfo);

   useEffect(()=>{      
       if(!loading) {
            ((userinfo==null)?
             /*API call A (When user is not logged in) */ :
            /*API call B (When user is logged in) */
            )
       }
    )},[loading, userinfo])  

   if(loading) return <Loader />
   return (
       (userinfo==null)?
       /*Elements to render when user is not logged in) */ :
       /*Elements to render when user is  logged in) */
   );
}

这篇关于React/React Context API:使用 useEffect() 钩子时等待上下文值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆