将数据从父组件传递到子组件但其他组件正在工作时,“类型错误:无法读取未定义的 x 的属性" [英] 'TypeError: Cannot read property of x of undefined' when passing data from parent to child component but others are working

查看:28
本文介绍了将数据从父组件传递到子组件但其他组件正在工作时,“类型错误:无法读取未定义的 x 的属性"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Overview.js

import React, { useState, useEffect } from 'react';从'./Statistics'导入统计信息;从 'axios' 导入 axios;导出默认函数概览(道具){const 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);const coinStats = 等待 fetchedData.data;setStatistics(coinStats);}使用效果(函数(){if (Object.keys(coin).length === 0 && Object.keys(statistics).length === 0) {fetchBasicData();}})//一些代码返回 (<div>//一些其他的东西<统计统计={统计}lastUpdate={statistics.last_updated}price={statistics.quotes.USD.price}//<----- 这是发生错误的地方/>

);}

Statistics.js

从'react'导入React;导出默认函数统计(道具){返回 (<div><h1>统计</h1><p>上次更新:{props.lastUpdate}</p><p>价格:{props.price}</p><p>市场排名:{props.marketRank}</p><h2>供应</h2><p>循环供应:{props.circulatingSupply}</p><p>最大供应量:{props.maxSupply}</p>

);}

解决方案

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

改变

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

这篇关于将数据从父组件传递到子组件但其他组件正在工作时,“类型错误:无法读取未定义的 x 的属性"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆