英文:
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 '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}`) //LOADS ME UNDEFINED "user?.id"
.then(response=>{
setData(response.data);
}).catch(error=>{
console.log(error);
})
}
useEffect(()=>{
const interval = setInterval(() => {
peticionGet();
}, 2000);
return () => setInterval(interval);
},[])
if(user)
{
return (
<div>
{console.log("HERE LOADS THE VARIABLE WITHOUT PROBLEMS " + user?.id)}
</div>
</div>
)
}
else if(!user){
return"";
}
}
export default Perfil
<!-- end snippet -->
答案1
得分: 1
非常简单的修复。
- 检查在 useEffect 中是否设置了
user.id
。如果没有设置,就返回。 - 将
user
对象添加到 useEffect 的依赖数组中,以便在user
发生变化时重新触发。
useEffect(() => {
if (!user?.id) return;
const interval = setInterval(() => {
peticionGet();
}, 2000);
return () => clearInterval(interval);
}, [user])
英文:
Very simple fix.
- Check if
user.id
is set in the useEffect. If not, return. - Add the
user
object to the dependency array of useEffect to re-trigger, wheneveruser
changes
useEffect(() => {
if (!user?.id) return
const interval = setInterval(() => {
peticionGet();
}, 2000);
return () => setInterval(interval);
}, [user])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论