[英]React - Error while rendering child component with prop passed from parent component
I have a problem while creating my react app.创建我的反应应用程序时遇到问题。 I'm fetching data from CoinGecko API to build a crypto tracking app, but when I pass the
data
prop from the parent App.js
to the child Info.js
.我正在从 CoinGecko API 获取数据以构建加密跟踪应用程序,但是当我将
data
道具从父App.js
传递给子Info.js
。 When I try to render the page it gives me Info.js:45 Uncaught TypeError: Cannot read properties of undefined (reading 'large')
.当我尝试渲染页面时,它给了我
Info.js:45 Uncaught TypeError: Cannot read properties of undefined (reading 'large')
。 I really don't understand why it happens.我真的不明白为什么会这样。
App.js应用程序.js
function App() {
const [isToggled, setIsToggled] = useState(false);
const [data, setData] = useState({});
const [coin, setCoin] = useState("bitcoin");
const getData = () => {
axios({
method: "GET",
url: `https://api.coingecko.com/api/v3/coins/${coin}?localization=en`,
})
.then((response) => {
console.log(response.data);
setData(response.data);
})
.catch((err) => {
console.log(err);
});
};
useEffect(() => {
getData(coin);
}, []);
return (
<div>
<HeaderContainer />
<Search getData={getData} coin={coin} setCoin={setCoin} />
<Info mcap={mcap} data={data} />
</div>
);
}
Info.js Info.js
function Info({ image, mcap, data }) {
return (
<div className="info-container">
<div className="left-column">
<div className="top-row">
<div className="coin-icon-container">
<img
className="coin-icon"
src={data.image.large}
alt="coin logo"
width="40px"
height="40px"
></img>
</div>
<div className="coin-name-container">
<p className="coin-name">{data.name}</p>
<p className="coin-abbr">{data.symbol}</p>
</div>
<div className="coin-MCAP-details">
<p className="coin-position">#{data.market_cap_rank}</p>
<p className="coin-MCAP">{data.market_data.market_cap.usd}</p>
</div>
The same error happens with the market cap in the second to last line of code.在倒数第二行代码中的市值也会出现同样的错误。
data.name
and data.symbol
render correctly. data.name
和data.symbol
正确呈现。
The response.json
file is very long, so i'll just put the important parts: response.json
文件很长,所以我只放重要部分:
Response.json响应.json
{
"id": "bitcoin",
"symbol": "btc",
"name": "Bitcoin",
"asset_platform_id": null,
.......
"image":{
"thumb": "https://assets.coingecko.com/coins/images/1/thumb/bitcoin.png?1547033579",
"small": "https://assets.coingecko.com/coins/images/1/small/bitcoin.png?1547033579",
"large": "https://assets.coingecko.com/coins/images/1/large/bitcoin.png?1547033579"
}
.........
}
SetData
is by default an empty object, and because Axios request is called in useEffect
. SetData
默认是一个空的 object,因为 Axios 请求在useEffect
中被调用。 On the first render Info
component receives empty data
object.在第一个渲染
Info
组件接收空data
object。
To way to solve it.想办法解决。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.