首页 > 解决方案 > 在使用 Fetch API React 渲染时使用 JSX 显示 API 信息

问题描述

我正在使用此 url 获取数据:

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;

标签: javascriptreactjsapireact-hooksjsx

解决方案


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>
);

推荐阅读