我正在使用以下网址获取数据:
并且我确定我的圆点表示法是正确的,但是当我尝试将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>
);