组件渲染
然后
效果运行,所以
<Redirect href={"unAuthStack"} />
将在效果运行和排队任何状态更新之前呈现和生效。
使用加载状态并等待这两个副作用完成可能是您需要做的。
例子:
const Home = () => {
const [isLoading, setIsLoading] = useState(true);
const [authenticated, setAuthenticated] = useState(null);
const [firstLaunch, setFirstLaunch] = useState(null);
useEffect(() => {
const loadData = async () => {
try {
// Wait for both calls to resolve
const [data, auth] = await Promise.all([
firstTimeLaunch(),
isAuthenticated(),
]);
setFirstLaunch(data);
setAuthenticated(auth);
} catch(error) {
// handle/ignore any errors/rejections
} finally {
// then clear the loading state after success/failure
setIsLoading(false);
}
};
loadData();
}, []); // <-- empty dependency, run once on component mount
// Check if component is still loading data
if (isLoading) {
return null; // or loading indicator/spinner/etc
}
if (firstLaunch) {
return <Redirect href={"onBoarding"} />;
} else if (authenticated) {
return <Redirect href={"authStackTabs"} />;
}
return <Redirect href={"unAuthStack"} />;
};