首页 > 解决方案 > 尝试保存状态时 axios 响应返回空数组或未定义,仅在控制台日志记录时返回有效响应

问题描述

此问题是附加到axios 响应工作时未保存状态响应和设置状态失败时的附加问题。

我没有得到我的问题的真正答案,并认为我应该举一些例子。

我不明白为什么当我打印我的回复时我看到了结果但是当我尝试将它保存在一个状态时我得到一个空数组(在响应本身中这意味着我的新状态将是一个空数组...)

我通过互联网进行了研究,发现的只是人们没有按应有的方式使用 promise 的示例,因此无法保存响应但可以打印它。

我的代码

useEffect(()=>{
       props.getAllOpen.then(res=>{
       let check = res.data.data;
       console.log(check); or [console.log(res.data.data)]
       });
},[]);

结果在控制台

数组(2)

0:{站:数组(2),_id:“60c5be4be3f2262294dff893”,类型:“d”}

1:{站:数组(2),_id:“60c5be4be3f2262294dff892”,类型:“d”}

我的问题

const [Data,setData] = useState([]);
useEffect(()=>{
       props.getAllOpen.then(res=>{
       setData(res.data.data);
       console.log(res.data.data);
       });
},[]);

结果在控制台

[]

我究竟做错了什么?任何帮助将不胜感激。

谢谢你花时间帮助我:)

--->完整组件<---

import {React,useEffect,useState} from 'react';
let dateFormat = require('dateformat');
const NotificationTable = (props)=>{
const [Data,setData] = useState([]);
    useEffect(()=>{
       props.getAllOpen.then(res=>{
        setData(res.data.data);
       });
   },[]);
        
    // get date return true if the date is the date of current day
    function isSameDay(date) {
        let today = new Date();
        if(today.getMonth()===date.getMonth() && today.getFullYear()===date.getFullYear() 
        && today.getDay()=== date.getDay())
            return true;

        return false;
    }
    return(
            <div className = "Notification-Table">
                <div className  = "Row"> <div className = "Header-Cell">end date</div><div className = "Header-Cell">start date</div> <div className = "Header-Cell">duplicate</div> <div className = "Header-Cell">סוג</div> <div className = "Header-Cell">s</div></div>
                { [...Data.filter(e=>e.Close==="1970-01-01T00:00:00.000Z").splice(0,21),...Array(22-Data.filter(e=>e.Close==="1970-01-01T00:00:00.000Z").splice(0,21).length)].map((d,index)=>{
                    if(d)
                   { 
                    return(<div key = {d._id} className  = "Row"> 
                    <div className = "Cell">{new Date(d.Close).getFullYear()===1970?"Live":isSameDay(new Date(d.Close))?dateFormat(new Date(d.Close),"HH:MM:ss"):dateFormat(new Date(d.Close),"dd-mm-yyyy")}</div>
                    <div className = "Cell">{isSameDay(new Date(d.Open))?dateFormat(new Date(d.Open),"HH:MM:ss"):dateFormat(new Date(d.Close),"dd-mm-yyyy")}</div>
                    <div className = "Cell">{d.Duplicate}</div>
                    <div className = "Cell">{d.Type}</div> 
                    <div className = "Cell">{d.Stations}</div>
                    </div>);}
                    else
                   {
                       return(<div key = {index} className  = "Row"> 
                    <div className = "Empty-Cell"></div>
                    <div className = "Empty-Cell"></div>
                    <div className = "Empty-Cell"></div>
                    <div className = "Empty-Cell"></div> 
                    <div className = "Empty-Cell"></div>
                    </div>);}
                    })}
            </div>
);
};

export default NotificationTable;

---> axios 请求 <---

export const getAllOpenNotification = ()=> api.get('/opennotifications');

--->猫鼬查询<---

getOpenNotification = async (req, res) => {
    await Notification.find({Close:"1970-01-01T00:00:00.000Z"}, (err, notifications) => {
        if (err) {
            return res.status(400).json({ success: false, error: err });
        }
        if (!notifications.length) {
            return res
                .status(200)
                .json({ success: true,data:[],error: `Open Notification not found` });
        }
        return res.status(200).json({ success: true, data: notifications });
    }).catch(err => console.log(err));
};

--->路线<--- *

router.get('/opennotifications',getOpenNotification);

标签: reactjsaxiosreact-hooks

解决方案


您没有做错任何事情,但是 console.log() 是异步函数。因此,当您打印 res.data.data 时,打印可能会在分配之前完成。所以即使分配已经完成,你也会得到一个空数组。

要解决此问题,您可以在此处查看


推荐阅读