【问题标题】:Showing API Information with JSX on render with Fetch API React在使用 Fetch API React 渲染时使用 JSX 显示 API 信息
【发布时间】:2021-03-11 07:13:20
【问题描述】:

我正在使用这个 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;

【问题讨论】:

    标签: javascript reactjs api react-hooks jsx


    【解决方案1】:

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

    您需要告诉 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>
    );
    

    【讨论】:

      【解决方案2】:

      当组件被挂载时,smallData[0-3] 还不存在,因为 fetch 调用尚未执行。 React 正在尝试使用 smallData 变量在它被正确定义之前渲染你的 JSX,从而导致错误。

      您的 JSX 模板需要考虑到,在第一次挂载时,数据仍将被加载且尚未准备好。因此,在变量准备好之前,您应该显示其他内容。

      首先,将smallData初始化为未定义:useState({}) > useState(undefined)

      然后,更新 JSX 以仅在数据准备好时显示 SmallBox 元素,并在数据准备好之前显示加载标签。

        return (
          <div className="app">
            {!smallData && <div>Loading...</div>}
            {smallData && <div>
              {/* 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>}
          </div>
        );
      

      还有其他一些事情需要考虑,例如获取失败时的错误状态,但这应该可以让您启动并运行。

      【讨论】:

        猜你喜欢
        • 2020-11-16
        • 2018-03-10
        • 2022-11-22
        • 2018-05-23
        • 2021-12-26
        • 2019-07-31
        • 2019-08-01
        • 1970-01-01
        • 2019-02-02
        相关资源
        最近更新 更多