[英]How to Make A second API call based on the value gotten from the first. with React and useEffect hooks
[英]Make an API call on second render using React Hooks
我想做的是從天氣 API 中獲取數據,但是在第一次渲染時會發生“數據”state 是空的,而在第二次渲染時 API 被稱為數據集。 這使得當我稍后嘗試訪問圖像的數據時出現錯誤TypeError: Cannot read property 'weather' of undefined
,因為它最初是空的。 不知何故,我需要跟蹤渲染發生的次數或更改我獲取數據的方式。 我認為使用空列表作為第二個參數的useEffect
將充當componentDidMount
。 這是我的代碼:
import React, {useState, useEffect} from 'react';
export default function App() {
const useFetch = () =>{
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
useEffect( () => {
async function fetchData(){
const response = await fetch('https://api.weatherbit.io/v2.0/forecast/hourly?city=Chicago,IL&key=XXX&hours=24');
const json = await response.json();
setData(json.data);
setLoading(false);
}
fetchData();
}, []);
return {data, loading};
}
const convert = (c) =>{
let f = (c*(9/5))+32;
return f
}
const {data, loading} = useFetch();
console.log(data)
return (
<div>
<img src={'https://www.weatherbit.io/static/img/icons/'+data[0].weather.icon+'.png'}/>
<h1>{loading ? 'Loading...' : ''}</h1>
</div>
)
}
傳遞給useEffect
的 function 將在渲染提交到屏幕后運行,默認情況下,效果在每次完成渲染后運行。 僅當 api 調用完成時,即 loading 為false
時,您才需要渲染img
。
import React, {useState, useEffect} from 'react';
export default function App() {
const useFetch = () =>{
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
useEffect( () => {
async function fetchData(){
const response = await fetch('https://api.weatherbit.io/v2.0/forecast/hourly?city=Chicago,IL&key=XXX&hours=24');
const json = await response.json();
setData(json.data);
setLoading(false);
}
fetchData();
}, []);
return {data, loading};
}
const convert = (c) =>{
let f = (c*(9/5))+32;
return f
}
const {data, loading} = useFetch();
if(loading) {
return <h1>{'Loading...'}</h1>
}
return (
<div>
<img src = {'https://www.weatherbit.io/static/img/icons/'+data[0].weather.icon+'.png'}/>
</div>
)
}
你可以試試這樣的
const [data, setData] = useState(null);
return (
{data ? ( <div>
<img src={'https://www.weatherbit.io/static/img/icons/'+data[0].weather.icon+'.png'}/>
<h1>{loading ? 'Loading...' : ''}</h1>
</div>) : <p>Loading....<p>}
)
這將數據設置為 null 在第一次渲染和渲染中的條件渲染 function 檢查數據是否為真/或有數據,如果沒有返回加載...文本
您可以在渲染中添加條件 function
return (
<div>
{data && data.weather && <img src={'https://www.weatherbit.io/static/img/icons/'+data[0].weather.icon+'.png'}/>}
<h1>{loading ? 'Loading...' : ''}</h1>
</div>
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.