javascript - 在使用 Fetch API React 渲染时使用 JSX 显示 API 信息
问题描述
我正在使用此 url 获取数据:
而且我确定我的点表示法是正确的,但是当我尝试将我的 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;
解决方案
React 需要随时知道要渲染什么。最初渲染组件时,尚未设置外部数据。此时smallData[0]
将评估为undefined
。调用.name
会undefined
导致你遇到的错误。
您需要告诉 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>
);
推荐阅读
- react-native - 反应原生 headerRight 菜单不触发
- android - Highcharts - 一段时间后缓慢的动态图形 ANDROID
- mysql - 如何设置MySql远程数据库
- express - 如何使用 Express 请求方法 post
- c# - StatusCode:403,ReasonPhrase:'Forbidden',版本:1.1,.. - Instagram 登录
- python-3.x - 在python的文本文件中将分隔符更改为多字符分隔符
- c# - 移动到 nuget 包后获取环境变量的不同行为
- python - 使用 python zeep 验证后打印 WSDL 文件
- css - 为什么当我将行跨度设置为列时,bootstrap4 表中的单元格边框会消失?
- flutter - 颤动中带有同步融合的烛台