Warm tip: This article is reproduced from serverfault.com, please click

javascript-使用Fetch API React在渲染中使用JSX显示API信息

(javascript - Showing API Information with JSX on render with Fetch API React)

发布于 2020-11-28 23:11:12

我正在使用以下网址获取数据:

https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=100&page=1&sparkline=false

并且我确定我的圆点表示法是正确的,但是当我尝试将api信息传递给子组件时,会引发错误。

在此处输入图片说明

我认为这与async / await有关,或者在呈现页面时,尚无法读取数据。但是我不确定

import React, {useState, useEffect} from 'react';
import SmallBox from './SmallBox';
import './App.css';

function App() {
  const [smallData, setSmallData] = useState({})

  useEffect(() => {
    fetch(`https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=100&page=1&sparkline=false`)
    .then(response => response.json())
    .then(data => {
      setSmallData(data)
    })
  })

  return (
    <div className="app">    
      {/* SmallBox - bitcoin */}
      <SmallBox className="bitcoin" title={smallData[0].name}/>
      
      {/* SmallBox - ethereum */}
      <SmallBox className="ethereum" title={smallData[1].name}/>
      
      {/* SmallBox - ripple */}
      <SmallBox className="ripple" title={smallData[2].name}/>
      
      {/* SmallBox - tether */}
      <SmallBox className="tether" title={smallData[3].name}/>

    </div>
  );
}

export default App;
Questioner
Owen Osagiede
Viewed
0
3limin4t0r 2020-11-29 07:37:31

React需要随时知道要渲染什么。最初渲染组件时,尚未设置外部数据。此时smallData[0]将评估为undefined调用.nameundefined会导致你遇到的错误。

你需要告诉React在获取数据时要渲染什么,这就像说什么都不需要渲染(返回null)一样简单。

// amusing a initial value of null is used for smallData (to simplify the answer)
const [smallData, setSmallData] = useState(null);

// ...

if (!smallData) return null; // <- render nothing

return (
  <div className="app">
    {/* ... */}
  </div>
);

你可以根据需要使事情复杂,并渲染精美的加载组件/场景/视图。

if (!smallData) return <Loading />;
// or
if (!smallData) return renderLoading();

return (
  <div className="app">
    {/* ... */}
  </div>
);