首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >控制台日志响应数据返回数据,但不是状态

控制台日志响应数据返回数据,但不是状态
EN

Stack Overflow用户
提问于 2020-12-03 23:53:50
回答 3查看 60关注 0票数 1

当我在loadingData()中执行console.log(response.data)时,它以2个数组的形式返回结果:

代码语言:javascript
运行
复制
{user: {…}, postedby: Array(2)}

以下是控制台日志的代码:

代码语言:javascript
运行
复制
 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)时,它返回一个空数组:

代码语言:javascript
运行
复制
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) 
          
        }

我迷失了,想知道我错过了什么。任何帮助都非常感谢,并提前表示感谢。谢谢

EN

回答 3

Stack Overflow用户

发布于 2020-12-04 00:02:36

这是因为只有在挂载组件时才会调用具有空依赖数组的useEffect。所以在那时,userProfile是一个空数组。这是因为loadingData()是一个异步函数。

因此,执行流程如下所示:

empty.

  • Execute loadingData().

  • Update userProfile

状态下的

  1. Call empty.
  2. ExecuteloadingData().
  3. UpdateuserProfile

日志userProfile

所以你现在可以做的就是使用2个useEffect,一个用一个空的依赖数组调用loadingData(),另一个用userProfile把它记录在依赖数组中。

像这样

代码语言:javascript
运行
复制
useEffect(()=>{
  console.log(userProfile) 
},[])

useEffect(()=>{
  console.log(userProfile) 
},[userProfile])

现在,每次更新userProfile时,都会调用依赖项数组中具有userProfileuseEffect,从而将其记入日志。

有关useEffect和依赖项数组的信息,请参阅here

票数 2
EN

Stack Overflow用户

发布于 2020-12-04 00:06:44

您需要2个useEffect:1个触发函数,1个捕获userProfile状态值的变化,

如果你只使用一个useEffect来做这两个动作,你会进入无限循环,因为你会在每次userProfile改变时执行这个函数,但是你的函数改变了这个值……

代码语言:javascript
运行
复制
   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])
票数 1
EN

Stack Overflow用户

发布于 2020-12-04 00:00:36

我非常确定在react中设置状态是异步的,所以你不会立即看到它的反映。在幕后,react批处理对设置状态的调用,这样它就不会在每次状态更改时呈现组件

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65129405

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档