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

#39;TypeError: Cannot read property of x of undefined#39; when passing data from parent to child component but others are working(TypeError: Cannot read property of x of undefined 将数据从父组件传递到子组件但其他组件正在工作)

本文介绍了'TypeError: Cannot read property of x of undefined' 将数据从父组件传递到子组件但其他组件正在工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

美好的一天,我有一个项目从 API 获取响应,然后将数据从父级传递给子级.问题是,我可以轻松访问顶层的响应,但是当我尝试进入 API 的内部时(在本例中,price={statistics.quotes.USD.price}) ,我收到 TypeError: Cannot read property 'USD' of undefined 错误.我试过控制台.记录价格以检查我的路径是否正确.当我可以正确访问其他数据时,为什么会发生这种情况?

Overview.js

import React, { useState, useEffect } from 'react';从'./Statistics'导入统计数据;从'axios'导入axios;导出默认功能概览(道具){常量 id = props.match.params.currency;//这里的一些其他状态const [统计,setStatistics] = useState({});//一些代码const fetchBasicData = async () =>{//检索硬币的基本信息const apiCall = await axios.get('https://api.coinpaprika.com/v1/coins/' + id);让 basicData = 等待 apiCall.data;setCoin(基本数据);//检索硬币统计信息const fetchedData = await axios.get('https://api.coinpaprika.com/v1/tickers/' + id);常量 coinStats = 等待 fetchedData.data;集合统计(coinStats);}使用效果(函数(){if (Object.keys(coin).length === 0 && Object.keys(statistics).length === 0) {fetchBasicData();}})//一些代码返回 (

//一些其他的东西<统计统计={统计}lastUpdate={statistics.last_updated}price={statistics.quotes.USD.price}//<----- 这是错误发生的地方/></div>);}

Statistics.js

从'react'导入反应;导出默认函数统计(道具){返回 (

<h1>统计数据</h1><p>最后更新:{props.lastUpdate}</p><p>价格:{props.price}</p><p>市场排名:{props.marketRank}</p><h2>供应</h2><p>循环供给:{props.circulatingSupply}</p><p>最大供应量:{props.maxSupply}</p></div>);}

解决方案

您好,可能是您的数据中的某些行没有引号,请尝试进行以下更改,它应该由此修复

改变

price={statistics.quotes.USD.price}

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

?检查给定变量是否存在,如果不存在则返回 null 并且不抛出错误

Good day, I have a project that gets a response from an API then passes down the data from parent to child. 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. 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

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

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

这篇关于'TypeError: Cannot read property of x of undefined' 将数据从父组件传递到子组件但其他组件正在工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

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

基础教程推荐