简体   繁体   English

'TypeError: Cannot read property of x of undefined' 将数据从父组件传递到子组件但其他组件正在工作

[英]'TypeError: Cannot read property of x of undefined' when passing data from parent to child component but others are working

Good day, I have a project that gets a response from an API then passes down the data from parent to child.美好的一天,我有一个项目得到 API 的响应,然后将数据从父级传递给子级。 The problem is, I can easily access the response at the top level but when I try to get in the inner parts of the API (in this case, the price={statistics.quotes.USD.price} ), I'm getting the TypeError: Cannot read property 'USD' of undefined error.问题是,我可以轻松访问顶层的响应,但是当我尝试进入 API 的内部时(在这种情况下, price={statistics.quotes.USD.price} ),我得到了TypeError: Cannot read property 'USD' of undefined错误。 I have tried console.logging the price to check if my path is correct and it is.我试过控制台。记录价格以检查我的路径是否正确。 Why could this be happening when I can access other data correctly?当我可以正确访问其他数据时,为什么会发生这种情况?

Overview.js概述.js

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

export default function Overview(props) {
    const id = props.match.params.currency;

    //some other states here

    const [statistics, setStatistics] = useState({});

    //some code

    const fetchBasicData = async () => {
        // Retrieves a coin's basic information
        const apiCall = await axios.get('https://api.coinpaprika.com/v1/coins/' + id);
        let basicData = await apiCall.data;

        setCoin(basicData);
            
        // Retrieves coin statistics
        const fetchedData = await axios.get('https://api.coinpaprika.com/v1/tickers/' + id);
        const coinStats = await fetchedData.data;

        setStatistics(coinStats);
    }

    useEffect(function () {
        if (Object.keys(coin).length === 0 && Object.keys(statistics).length === 0) {
            fetchBasicData();
        }
    })

    //some code

    return (
        <div>
            //some other stuff
            <Statistics
                statistics={statistics}
                lastUpdate={statistics.last_updated}
                price={statistics.quotes.USD.price}          // <----- this is where the error occurs
             />
        </div>
    );
}

Statistics.js Statistics.js

import React from 'react';

export default function Statistics(props) {
    return (
        <div>
            <h1>Statistics</h1>
            <p>Last updated: {props.lastUpdate}</p>
            <p>Price: {props.price}</p>
            <p>Market Rank: {props.marketRank}</p>
            <h2>Supply</h2>
            <p>Circulating supply: {props.circulatingSupply}</p>
            <p>Max supply: {props.maxSupply}</p>
        </div>
    );
}

Hi it could be that some of rows in your data do not have quotes try doing following change it should be fixed by this嗨,可能是您的数据中的某些行没有引号尝试进行以下更改,它应该由此修复

change改变

price={statistics.quotes.USD.price}

to

price={statistics?.quotes?.USD?.price}

? ? checks if given variable is present and if not return null and does not throw an error检查给定变量是否存在,如果不存在则返回 null 并且不抛出错误

As you are using the axios call, which is asynchronous and the data of that call is not available on initial render, but it will be available later on.由于您正在使用axios调用,这是异步的,并且该调用的数据在初始渲染时不可用,但稍后将可用。 So to handle this you have to conditional render (render only when certain condition met)因此,要处理此问题,您必须有条件渲染(仅在满足特定条件时渲染)

Try this:尝试这个:

price={statistics?.quotes?.USD?.price}

Or you can also use Object.hasOwnProperty('key') with ternary and do the conditional render.或者您也可以将Object.hasOwnProperty('key')ternary一起使用并进行条件渲染。

Issue问题

Error: TypeError: Cannot read property 'USD' of undefined is saying that statistics.quotes is undefined.错误: TypeError: Cannot read property 'USD' of undefined是说statistics.quotes未定义。

There are 2 possible causes:有2个可能的原因:

  1. On the initial render you are accessing too deeply into your initial state.在初始渲染中,您对初始 state 的访问过于深入。
  2. On any subsequent render the statistics isn't updated to something you're expecting.在任何后续渲染中, statistics都不会更新为您所期望的。

My guess is that your data fetching and state update is fine and it's just the initial render issue.我的猜测是您的数据获取和 state 更新很好,这只是初始渲染问题。

The initial statistics state is an empty object ( {} ), so accessing any property is fine.初始statistics state 是一个空的 object ( {} ),因此访问任何属性都可以。 It's when you then go a nested level deeper into the structure that causes the issue.正是当您将 go 嵌套到更深的结构中时,才会导致问题。

<Statistics
  statistics={statistics} // OK: statistics => {}
  lastUpdate={statistics.last_updated} // OK: statistics.last_updated => undefined
  price={statistics.quotes.USD.price} // Error: can't access USD of undefined statistics.quotes
/>

 const statistics = {}; console.log(statistics); // {} console.log(statistics.quotes); // undefined console.log(statistics.qoutes.USD); // error!!

Solution解决方案

You can use Optional Chaining operator ( ?. ) or guard clauses (null checks) to protect the "access X of undefined" errors.您可以使用可选链接运算符( ?. ) 或保护子句(空检查)来保护“未定义的访问 X”错误。

<Statistics
  statistics={statistics}
  lastUpdate={statistics.last_updated}
  price={statistics.quotes?.USD?.price}
/>
<Statistics
  statistics={statistics}
  lastUpdate={statistics.last_updated}
  price={statistics.quotes && statistics.quotes.USD && statistics.quotes.USD.price}
/>

If there's even a remote chance that your statistics state can be updated to undefined then apply the same fix as above but just a level shallower, ie statistics?.quotes?.USD?.price .如果您的statistics state 可以更新为undefined的可能性很小,那么应用与上述相同的修复,但只是更浅的级别,即statistics?.quotes?.USD?.price

Alternatively you can apply some Conditional Rendering of the Statistics component where the condition is the nested properties existing on the statistics state.或者,您可以应用Statistics组件的一些条件渲染,其中条件是statistics state 上存在的嵌套属性。

return (
  <div>
    //some other stuff
    {statistics.last_updated && statistics.quotes && (
      <Statistics
        statistics={statistics}
        lastUpdate={statistics.last_updated}
        price={statistics.quotes.USD?.price}
      />
    )}
  </div>
);

暂无
暂无

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

相关问题 将 axios 获取的道具从父级传递给子级返回“类型错误:无法读取未定义的属性 &#39;x&#39;” - Passing axios fetched prop from Parent to Child returns “TypeError: Cannot read property 'x' of undefined” TypeError:无法读取未定义的属性“ stateUpdate”(哪个函数)/将数据从父级传递到子级 - TypeError: Cannot read property 'stateUpdate' (Which is a function) of undefined / Passing data from Parent to child TypeError:无法将子组件中未定义的属性“setState”读取到父组件 - TypeError: Cannot read property 'setState' of undefined in child to parent component TypeError: Cannot read property 'map' of undefined 当我尝试 map 通过从父组件传递到子组件的道具时显示 - TypeError: Cannot read property 'map' of undefined is showing when I'm trying to map over the props passed from parent component to child component 使用window.open将数据从父级传递到子级时,为什么会显示“无法读取未定义的属性”元素”? - When passing data from parent to child with window.open, why do I get 'Cannot read property 'elements' of undefined'? 将值从子组件传递到父组件时无法读取“目标”属性 - Cannot read “target” property when passing value from child to parent component TypeError:无法读取 React 组件内未定义的属性“名称”,用作另一个父组件内的子组件 - TypeError: Cannot read property 'name' of undefined inside React component used as child inside another parent component 尝试从vue.js中的子组件将数据推送到数组,但出现TypeError:无法读取未定义的属性“ push”” - Trying to push data to an array from a child component in vue.js but get TypeError: Cannot read property 'push' of undefined" Vue:单击按钮时从父组件更改子组件的数据无法设置未定义的属性 - Vue: change data of child component from parent component on button click Cannot set property of undefined 未捕获的TypeError:当存在父级时,无法读取未定义的属性“长度” - Uncaught TypeError: Cannot read property 'length' of undefined when there is a parent
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM