简体   繁体   English

CoinGecko API 数据在重新渲染 React JS 后未定义

[英]CoinGecko API data undefined after re-render React JS

Trying to render data from the CoinGekco API in my React component.尝试在我的 React 组件中呈现来自CoinGekco API的数据。 It works on first render but if I leave the page or refresh, coin.market_data is undefined.它适用于第一次渲染,但如果我离开页面或刷新,coin.market_data 未定义。 I also tried passing coin to the useEffect() dependency array and that didn't work.我还尝试将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;

The GET request only happens when rendering the parent page. GET request仅在呈现父页面时发生。 Re-rendering the child component will not run the fetch code again.重新渲染子组件不会再次运行获取代码。 Instead of passing current_price as a prop to your <CoinDetail> component, you could try passing coinid and doing the fetch inside your detail page.除了将current_price作为道具传递给<CoinDetail>组件之外,您还可以尝试传递coinid并在您的详细信息页面中进行获取。

That way, when the page is refreshed, the request will be executed again.这样,当页面刷新时, request将再次执行。

Edit编辑

If you try to access a not existing property on an object, your application will crash.如果您尝试访问 object 上不存在的属性,您的应用程序将崩溃。 What you could do to prevent this from happening is checking if the request is done, before trying to access the property.为了防止这种情况发生,您可以做的是在尝试访问该属性之前检查request是否已完成。

One way you could do this by setting the initial state value to null一种方法是通过将初始 state 值设置为null

const [coin, setCoin] = useState(null);

Then, above the main return , you could check if the value is null , if it is, return some sort of loading screen然后,在 main return上方,您可以检查该值是否为null ,如果是,则返回某种加载屏幕

if(coin === null) return <LoadingScreen />;

// main render
return (
  <div>
    <CoinDetail current_price={coin.market_data.current_price.usd} />
  </div>
);

This way, when the fetch is done, the state gets updated and the page will re-render and show the updated content.这样,当获取完成时,state 将得到更新,页面将重新渲染并显示更新的内容。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM