我有一個國家串列組件,其中包含國家電話代碼、國家名稱及其使用map()功能的標志,因此加載時間有點長。如果功能結束或仍在作業,我需要獲取資訊,map()然后使用它來顯示然后隱藏占位符。我怎么能做到這一點?
我在 Internet 上找不到合適的解決方案或無法使用它們。就像Promise(all)在 React 組件中使用時一樣,我一直很難弄清楚語法應該是怎樣的。
<CountryList />零件:
// Packages I used for countries
import { getCountries, getCountryCallingCode } from "react-phone-number-input"
import countryNames from "react-phone-number-input/locale/en.json"
import ReactCountryFlag from "react-country-flag"
// The array comes from package
const countries = getCountries()
<CountryList>
{countries.map((country) => (
<CountryItem key={country} value={country}>
<ReactCountryFlag countryCode={country} svg />
<span>
{countryNames[country]}
<span> {getCountryCallingCode(country)}</span>
</span>
</CountryItem>
))}
</CountryList>
<CountryItemSkeleton />零件:
// The package I used for skeleton placeholder
import ContentLoader from "react-content-loader"
<CountryItemSkeleton>
<CountryItem>
<ContentLoader>
<rect x="0" y="0" rx="3" ry="3" width="40" height="30" />
<rect x="52" y="8" rx="7" ry="7" width="248" height="14" />
</ContentLoader>
</CountryItem>
<CountryItem>
<ContentLoader>
<rect x="0" y="0" rx="3" ry="3" width="40" height="30" />
<rect x="52" y="8" rx="7" ry="7" width="248" height="14" />
</ContentLoader>
</CountryItem>
<CountryItem>
<ContentLoader>
<rect x="0" y="0" rx="3" ry="3" width="40" height="30" />
<rect x="52" y="8" rx="7" ry="7" width="248" height="14" />
</ContentLoader>
</CountryItem>
</CountryItemSkeleton>
uj5u.com熱心網友回復:
這里的一切都是同步的,所以你不能等待或監控map()進度。
您可以嘗試將國家/地區串列加載到效果掛鉤中,以便在安裝組件后填充它。在初始渲染中,您可以使用骨架組件
const [countries, setCountries] = useState([]);
// run once on mount
useEffect(() => {
setCountries(getCountries());
}, []);
// or even with a small delay
useEffect(() => {
const timer = setTimeout(setCountries, 200, getCountries());
return () => {
clearTimeout(timerId);
};
}, []);
return countries.length === 0 ? (
<CountryItemSkeleton />
) : (
<CountryList>
{countries.map((country) => (
<CountryItem key={country} value={country}>
{/* etc */}
</CountryItem>
))}
</CountryList>
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/453487.html
標籤:javascript 数组 反应 字典 jsx
