尝试在React组件中呈现来自CoinGekco API的数据。它在第一次呈现时有效,但如果我离开页面或刷新,coin.market_data是未定义的。我还尝试将coin传递给useEffect()依赖项数组,但没有成功。
import React, { useEffect, useState } from "react";
import axios from "../utils/axios";
import CoinDetail from "./CoinDetail";
function CoinPagePage() {
const [coin, setCoin] = useState({});
useEffect(() => {
const getCoin = () => {
const coinid = window.location.pathname.split("/").splice(2).toString();
axios
.get(`/coins/${coinid}`)
.then((res) => {
setCoin(res.data);
console.log(res.data);
})
.catch((error) => console.log(error));
};
getCoin();
}, []);
return (
<div>
<CoinDetail current_price={coin.market_data.current_price.usd} />
</div>
);
}
export default CoinPagePage;发布于 2021-06-09 21:48:16
GET request仅在呈现父页面时发生。重新渲染子组件将不会再次运行获取代码。您可以尝试传递coinid并在详细页中进行获取,而不是将current_price作为道具传递给<CoinDetail>组件。
这样,当页面刷新时,request将再次执行。
编辑
如果您尝试访问对象上不存在的属性,您的应用程序将崩溃。为了防止这种情况发生,您可以在尝试访问该属性之前检查request是否已完成。
一种方法是将初始状态值设置为null
const [coin, setCoin] = useState(null);然后,在主return之上,您可以检查该值是否为null,如果是,则返回某种加载屏幕
if(coin === null) return <LoadingScreen />;
// main render
return (
<div>
<CoinDetail current_price={coin.market_data.current_price.usd} />
</div>
);这样,当获取完成时,状态得到更新,页面将重新呈现并显示更新后的内容。
https://stackoverflow.com/questions/67904824
复制相似问题