import React, { useEffect, useState } from 'react';
import { Spinner } from 'react-bootstrap';
import Country from '../Country/Country'
const Countries = () => {
const[countries,setCountries]=useState([])
const [isLoading,setLoading]=useState(true)
useEffect(()=>{
fetch('https://restcountries.com/v3.1/all')
.then(res=>res.json())
.then(data=>setCountries(data))
setLoading(false)
},[])
return (
<div className='container'>
<div className="row row-cols-lg-4 row-cols-md-2 row-cols-sm-1 row-cols-1 g-2 mt-3">
{
isLoading?<Spinner animation='border'/>:countries.map(country=><Country key={Math.random(1,10)} country={country} />)
}
</div>
</div>
);
};
export default Countries;
Spinner 在 { } 之外作業。但是當我嘗試這個時->
{isLoading?<Spinner animation='border'/>:countries.map(country=><Country key={Math.random(1,10)} country={country} />)}.
它不作業。我想說在資料顯示之前它沒有顯示任何微調器
uj5u.com熱心網友回復:
回應到達后嘗試禁用微調器:
useEffect(()=>{
fetch('https://restcountries.com/v3.1/all')
.then(res=>res.json())
.then(data=>{
setCountries(data)
setLoading(false)
})
我建議您僅使用國家/地區:
const[countries,setCountries]=useState(null)
....
!countries?<Spinner animation='border'/>:countries.map(....
},[])
uj5u.com熱心網友回復:
首先,在獲取資料時將 setLoading 設為 false:
useEffect(() => {
fetch("https://restcountries.com/v3.1/all")
.then((res) => res.json())
.then((data) => {
setCountries(data);
setLoading(false);
});
}, []);
使用一個函式來渲染國家的良好實踐:
const renderCountries = () => {
countries.map((country) => (
<Country key={Math.random(1, 10)} country={country} />
));
};
最后,檢查 isLoading 然后 show spinner other 呼叫函式來顯示國家:
{isLoading ? <Spinner animation="border" /> : renderCountries()}
uj5u.com熱心網友回復:
您應該isLoading在回傳之前記錄正確的內容。您還應該將狀態更改放在最后then,以確認有資料并且已完成檢索。
useEffect(()=>{
fetch('https://restcountries.com/v3.1/all')
.then(res=>{
if (!res.ok){
console.log(res)
} else {
res.json()
}
}).then(data=>{
setCountries(data)
setLoading(false) // here is the state change
})
})
uj5u.com熱心網友回復:
Promise 是異步的, setLoading(false)不會等待回應。它只會更新狀態。資料接收時放置setLoading 。
.then(data=>{
setCountries(data)
setLoading(false)
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/451946.html
標籤:javascript 反应 反应路由器
上一篇:如何在Javascript中使用“for”回圈創建二維陣列?
下一篇:按字母排序后鏈接未更改
