变量加载我未定义的ReactJS。

huangapple go评论67阅读模式
英文:

variable loads me undefined reactjs

问题

我有一个会话变量user?.id,只有在加载项目后才会加载,这意味着第一次加载时它显示为未定义,然后重新加载项目后,它会加载相应的值,但这会导致我的axios中的GET出现错误,因为第一次加载时它会将其视为未定义,从而触发一系列错误,我的GET不会加载,我尝试解决它,但未能成功。

import React, { useContext, useState, useEffect } from 'react';
import { MyContext } from '../../login/MyContext';
import axios from 'axios';

function Perfil() {

    const { user } = useContext(MyContext);
    const [data, setData] = useState([]);

    const peticionGet = async () => {
        await axios.get(`https://aliraweb.com/apiAliraweb/perfil_img/index.php?id_p=${user?.id}`)
            .then(response => {
                setData(response.data);
            })
            .catch(error => {
                console.log(error);
            });
    }

    useEffect(() => {
        const interval = setInterval(() => {
            peticionGet();
        }, 2000);
        return () => clearInterval(interval);
    }, []);

    if (user) {
        return (
            <div>
                {console.log("这里正常加载变量:" + user?.id)}
            </div>
        )
    } else if (!user) {
        return "";
    }
}

export default Perfil;

请注意,我已经将你的代码部分翻译成中文,如果还有其他需要,请提出。

英文:

I have a session variable user?.id that only loads after having loaded the project, it means that the first time it loads it shows as undefined and after reloading the project it loads me with the corresponding value but it is causing an error in my GET in axios because when loading it the first time it detects it as undefined and that triggers a series of errors and my GET does not load, I have tried to solve it but I have not been able to achieve it.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

 import React, {useContext,useState,useEffect} from &#39;react&#39;;
    import {MyContext} from &#39;../../login/MyContext&#39;

    import axios from &#39;axios&#39;;

    function Perfil() {

        const {user} = useContext(MyContext); 
      
      const [data, setData]=useState([]);
        
     
        const peticionGet =async() =&gt;{
                   
            await axios.get(`https://aliraweb.com/apiAliraweb/perfil_img/index.php?id_p=${user?.id}`) //LOADS ME UNDEFINED &quot;user?.id&quot;
            .then(response=&gt;{
             setData(response.data);
            }).catch(error=&gt;{
              console.log(error);
            })
        
          }


      useEffect(()=&gt;{
        const interval = setInterval(() =&gt; {  
           
           peticionGet();
           
         }, 2000);
       return () =&gt; setInterval(interval); 
       },[])

         
      
    if(user)
        {
      return (
     
    &lt;div&gt;
    {console.log(&quot;HERE LOADS THE VARIABLE WITHOUT PROBLEMS &quot; + user?.id)}
    &lt;/div&gt;

    &lt;/div&gt;
       
      )
    }

    else if(!user){
        return&quot;&quot;;
    }

    }

    export default Perfil

<!-- end snippet -->

答案1

得分: 1

非常简单的修复。

  1. 检查在 useEffect 中是否设置了 user.id。如果没有设置,就返回。
  2. user 对象添加到 useEffect 的依赖数组中,以便在 user 发生变化时重新触发。
useEffect(() => {
	if (!user?.id) return;
	const interval = setInterval(() => {
		peticionGet();
	}, 2000);
	return () => clearInterval(interval);
}, [user])
英文:

Very simple fix.

  1. Check if user.id is set in the useEffect. If not, return.
  2. Add the user object to the dependency array of useEffect to re-trigger, whenever user changes
useEffect(() =&gt; {
	if (!user?.id) return
	const interval = setInterval(() =&gt; {
		peticionGet();

	}, 2000);
	return () =&gt; setInterval(interval);
}, [user])

huangapple
  • 本文由 发表于 2023年7月28日 05:50:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76783606.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定