我有这个屏幕,我想看到ActivityIndicator
,直到所有设备被映射(未获取):
const MyScreen = () => {
const [devices, setDevices] = useState();
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
getDevices();
}, []);
const getDevices = async () => {
const pulledDevices = await fetchDevices();
setDevices(pulledDevices)
setIsLoading(false)
};
if (isLoading)
return (
<ActivityIndicator />
);
return (
<View >
{devices?.map((device) => {
return (
<View>
<Text>{device.name}</Text>
</View>
);
})}
</View>
);
};
映射这些设备需要一些时间。
我如何在这里实现ActivityIndicator
,直到所有devices
都被映射。
我建议您使用稍微复杂一点的async await钩子来处理这个问题。
useAsyncHook.js
const useAsync = asyncFunction => {
const [loading, setLoading] = useState(false);
const [result, setResult] = useState(null);
const [error, setError] = useState(null);
const execute = useCallback(async () => {
setLoading(true);
setResult(null);
setError(null);
try {
const response = await asyncFunction();
setResult(response);
setLoading(false);
} catch (error) {
setError(error);
setLoading(false);
}
}, [asyncFunction]);
useEffect(() => {
execute();
}, [execute]);
return { loading, result, error };
};
这是一个原始的异步钩子,可以通过多种方式增强,但它在这种状态下正确地处理加载状态。
用法:
const { loading, result, error } = useAsync(yourFunction);
if (loading) return null;
return <Component />;