我试图通过axios
呼叫获取Api
,使用嵌入在端点内的useContext
。在axios call
之前,userData
返回值,但在useEffect
内部,它是未定义的,我不知道为什么会发生这种情况。
你们会感兴趣的部分因为我已经导入了所有内容等等
/* Importing UseState, UseEffect */
import React, {useState, useEffect, useContext} from "react";
/* Importing Axios */
import axios from "axios";
/* Styles Import */
import "./Badges.styles.scss";
/* Context Imports */
import {UserContext} from "../../../context/UserContext";
const Badges = () => {
/* Axios call for badges starts */
/* Creating the UseState for the badges */
const {userData} = useContext(UserContext);
console.log(userData);
const [badges, setBadges] = useState()
const [loading, setLoading] = useState(false)
// /* Function to fetch the Api */
// /* Making the Axios call */
useEffect(() => {
console.log(userData)
axios.get(`/api/v1/user/gamification/${userData._id}`)
.then(res => {
setBadges(res.data);
})
.catch(err => console.log(err))
},[])
/* Axios call for badges ends */
return ( .....
useEffect(() => {
// assuming your userData is null initially
if(userData)
{
axios.get(`/api/v1/user/gamification/${userData._id}`)
.then(res => {
setBadges(res.data);
})
.catch(err => console.log(err))
}
},[userData])
最有可能的是,在触发useEffect
之前,用于获取userData
的钩子没有时间返回所需的值。如果您需要在每次userData
更改时执行一个请求,只需将其添加到useEffect
依赖数组,如果只有一次,那么在最后一步之外,添加一个检查,如果请求已经启动