当我在loadingData()
中执行console.log(response.data)
时,它以2个数组的形式返回结果:
{user: {…}, postedby: Array(2)}
以下是控制台日志的代码:
const[userProfile,setUserProfile] = useState([])
useEffect(()=>{
loadingData()
},[])
const loadingData = async() => {
const response = await Axios.get(`http://localhost:5000/api/user/user/${userid}`, {withCredentials:true})
setUserProfile(response.data)
console.log(response.data)
}
但是当我在useEffect
中执行console.log(userProfile)
时,它返回一个空数组:
const[userProfile,setUserProfile] = useState([])
useEffect(()=>{
loadingData()
console.log(userProfile)
},[])
const loadingData = async() => {
const response = await Axios.get(`http://localhost:5000/api/user/user/${userid}`, {withCredentials:true})
setUserProfile(response.data)
}
我迷失了,想知道我错过了什么。任何帮助都非常感谢,并提前表示感谢。谢谢
发布于 2020-12-04 00:02:36
这是因为只有在挂载组件时才会调用具有空依赖数组的useEffect
。所以在那时,userProfile
是一个空数组。这是因为loadingData()
是一个异步函数。
因此,执行流程如下所示:
empty.
loadingData()
.
userProfile
状态下的
loadingData()
.userProfile
日志userProfile
所以你现在可以做的就是使用2个useEffect
,一个用一个空的依赖数组调用loadingData()
,另一个用userProfile
把它记录在依赖数组中。
像这样
useEffect(()=>{
console.log(userProfile)
},[])
useEffect(()=>{
console.log(userProfile)
},[userProfile])
现在,每次更新userProfile
时,都会调用依赖项数组中具有userProfile
的useEffect
,从而将其记入日志。
有关useEffect
和依赖项数组的信息,请参阅here
发布于 2020-12-04 00:06:44
您需要2个useEffect
:1个触发函数,1个捕获userProfile
状态值的变化,
如果你只使用一个useEffect
来做这两个动作,你会进入无限循环,因为你会在每次userProfile
改变时执行这个函数,但是你的函数改变了这个值……
const[userProfile,setUserProfile] = useState([])
useEffect(()=>{
const loadingData = async() => {
const response = await Axios.get(`http://localhost:5000/api/user/user/${userid}`, {withCredentials:true})
setUserProfile(response.data)
}
loadingData();
},[])
useEffect(()=>{
console.log(userProfile)
},[userProfile])
发布于 2020-12-04 00:00:36
我非常确定在react中设置状态是异步的,所以你不会立即看到它的反映。在幕后,react批处理对设置状态的调用,这样它就不会在每次状态更改时呈现组件
https://stackoverflow.com/questions/65129405
复制相似问题