我有一个国家清单组件,其中包含国家电话代码,国家名称和他们的标志使用map()功能,所以它需要一点时间来加载。如果map()函数结束或仍然工作,我需要获取信息,然后使用它来显示然后隐藏占位符。我怎样才能做到这一点?
我无法在互联网上找到合适的解决方案,也无法使用它们。就像在React组件中使用Promise(all)一样,我一直很难理解语法应该是怎样的。
<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>发布于 2022-03-30 02:05:50
这里的一切都是同步的,因此您不能等待或监视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://stackoverflow.com/questions/71670450
复制相似问题