类型错误:无法读取属性'数据'未定义-无法访问对象&属性&超出Reactjs中的特定级别。 [英] TypeError: Cannot read property 'data' of undefined - can't access Object "props" beyond certain level in Reactjs

查看:0
本文介绍了类型错误:无法读取属性'数据'未定义-无法访问对象&属性&超出Reactjs中的特定级别。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用UseEffectReact中通过axios进行API调用。
我们使用useState

将响应设置为名为data的变量
const [data, setData] = useState({});
  setData(response);

响应来自NASA API,我们只收到此调用返回的一个对象(粘贴如下)。

因为我将响应命名为"data",并且它也有一个"data"键,所以如果我想记录URL,我知道我会输入console.log(data.data.url),这在我的app.jsmain函数中运行得很顺利。在我的card.js组件中,我可以成功地记录console.log(data)console.log(data.data),它给出的正是您所期望的,但当我console.log(data.data.url)(data.data.title)由于某种原因而变成undefined时,这会导致JSX的返回函数出现很大错误,站点不会加载:

 TypeError: Cannot read property 'data' of undefined error.

我不认为我的命名有任何错误,因为它在对象的更高级别上工作得很好,例如console.log(data.data)Works,我可以在我的眼前看到列出的下一级别属性。

我真的很安慰。正在记录:

{console.log('FROM INSIDE THE RETURN')}
{console.log(props.data)}  // works, displays object {}
{console.log(props.data.data)}  //works, displays object one level lower   
{console.log(props.data.data.url)}  // type error. You name the property.

不用说,这不起作用,这是我完成任务的第一个方法:

<img src={props.data.data.url}/>

这就是说,我们在团队领导的帮助下,通过如下方式刮掉了上游物体的顶层,使程序正常工作:

SetData(response.data)

// as opposed to 
SetData(response)

// and then using 
<img src={props.data.url}/>

所以我们不必到达道具的底部,但为了清楚起见,我想知道它为什么会对编译器产生影响,以及它对编译器有什么影响,特别是当它工作到n-1层时,其中n是对象的层数。

我甚至更改了其中一个数据变量的名称,以便‘data’不会重复,并且行为相同。

感谢您的帮助和见解!我非常感谢您能分享的任何见解以及对我的问题的反馈。

这是我正在使用的对象。

     {
        data: {
            copyright: "Bryan Goff",
            date: "2020-03-18",
            explanation: "What's happening behind...[truncated]...Florida, USA.",
            hdurl: "https://apod.nasa.gov/apod/image/2003/AntiCrepRays_Goff_3072.jpg",
            media_type: "image",
            service_version: "v1",
            title: "Anticrepuscular Rays over Florida",
            url: "https://apod.nasa.gov/apod/image/2003/AntiCrepRays_Goff_960.jpg"
        },
        status: 200,
        statusText: "OK",
        headers: {
            contenttype: "application/json"
        },
        config: {
            url: "https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY",
            method: "get",
            headers: {
                Accept: "application/json, text/plain, */*"
            },
            transformRequest: [
                null
            ],
            transformResponse: [
                null
            ],
            timeout: 0,
            xsrfCookieName: "XSRF-TOKEN",
            xsrfHeaderName: "X-XSRF-TOKEN",
            maxContentLength: -1
        },
        request: {}
    }

推荐答案

这确实是一个有趣的挑战。
让我们做一步一步的分析,看看我们是否同意:

// this initializes `data = {}` when the app first launches
const [data, setData] = useState({});

// Chances are, you are using this within the "useEffect"
// If so at that point, the above `data = response`
setData(response)
您最有可能在useEffect中调用axiosNASA API。
那么,让我们将范围缩小到API调用。

API调用通常是异步(非阻塞)的。
换句话说,这个数据获取过程不会阻止您的客户端执行其他"活动"。现在,让我们回到您的共享代码:

解释1:这可能是我们获取数据时发生的

// works, because initially "data = {}"
{console.log(props.data)}

// works, displays object one level lower
{console.log(props.data.data)}
// Explaining this...
// APIs are often backend apps that query a database for actual data. 
// This returned data is stored in "literals" (often arrays/lists/objects).

// type error. You name the property.
{console.log(props.data.data.url)}
// Based on the above explanation, 
// despite the second `data` being an Object literal, 
// "url" isn't yet defined since the API is still "querying" the database

解释2:可能是命名空间冲突

// If all is fine based on "explanation 1", 
// then this could be a "namespace" conflict during compilation.

// At compilation, JS finds two variables named "data"
// 1. The initial data value, 
   data = {}
// 2. The returned data key,
   {
     data: {...},
   }
// If we had a returned response as follows:
   results = {
     data: {...},
   }
// we probably would have something like this working 
{console.log(response.data.result.data.url)}

// And this might explains why these work...
{console.log(response.data.url)}
<img src={props.data.url}/>

请记住,我们在这里面对的是顽固的JavaScript。
这可能是许多大型Reactjs项目现在涉及TypeScript的原因。

这篇关于类型错误:无法读取属性&#39;数据&#39;未定义-无法访问对象&属性&超出Reactjs中的特定级别。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆