简体   繁体   English

reactjs data.length 在保存时可访问,但在浏览器刷新时不可访问

[英]reactjs data.length accessible on save but not when browser refresh

I don't get it, in console I see my api data(array of 10 objects) but if I access the "data.data.length" when I save the file, it works(show number: 10 in console) but when I refresh the browser, the error occur(Uncaught TypeError: Cannot read property 'length' of undefined).我不明白,在控制台中我看到了我的 api 数据(10 个对象的数组)但是如果我在保存文件时访问“data.data.length”,它可以工作(在控制台中显示编号:10)但是当我刷新浏览器,出现错误(未捕获的类型错误:无法读取未定义的属性“长度”)。

Also I found out that when my page refresh, it console.log "undefined" first then my array of 10 objects api data.....我还发现,当我的页面刷新时,它首先是 console.log“未定义”,然后是我的 10 个对象数组 api 数据.....

I am so lost, what am I doing wrong?我很失落,我做错了什么?

import React, { useState, useEffect } from 'react';
import '../App.css';
import axios from 'axios';

function App() {
    const [data, setData] = useState({});

    useEffect(() => {
        axios
            .get(
                'http://api.giphy.com/v1/gifs/search?q=cat&limit=10&api_key=1234567890'
            )
            .then(({ data }) => {
                setData(data);
            })
            .catch((error) => {
                console.log(error);
            });
    }, []);

    return (
        <>
      {console.log(data.data)}
        </>
    );
}

export default App;

In the beginning of your component execution you have在您的组件执行开始时,您有

const [data, setData] = useState({});

this is the first data you are using and this data is an empty object thats why data.data is undefined这是您正在使用的第一个数据,该数据是一个空对象,这就是 data.data 未定义的原因

Then your effect is executed and only after that data is updated in success case and remains the same in error(catch) state然后执行您的效果,并且仅在成功情况下更新该数据并在错误(捕获)状态下保持不变

So in case you want to use next code所以如果你想使用下一个代码

data.data.length
// you are calling something like
// data.undefined.length

which in your case is throws exactly what it suppose to throw - Uncaught TypeError: Cannot read property 'length' of undefined在你的情况下,它抛出的正是它想抛出的 - 未捕获的类型错误:无法读取未定义的属性“长度”

I would suggest you to use next piece of code if you like to use length如果您喜欢使用长度,我建议您使用下一段代码

const length = data?.data?.length;

read more here Optional Chaining在此处阅读更多信息可选链

As the second option you can set starting state as作为第二个选项,您可以将起始状态设置为

const [data, setData] = useState({data:[]})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM