在 React Native SetState 中,即使我的函数提供了所需的输出(如 true 或 false),在初始渲染的 index.js 中也不起作用

问题描述 投票:0回答:1

这就是我正在尝试的,在 conrtrolFirstLaunch 和 getAuthentication 的功能中,我获取了数据和身份验证的日志,但状态没有更新,我不知道为什么会发生这种情况,但在实现首次启动之前它工作正常

import React, { useState, useEffect } from "react";
import { isAuthenticated, firstTimeLaunch } from "Services/Auth";
import { Redirect } from "expo-router";

const Home = () => {
  const [authenticated, setAuthenticated] = useState(null);
  const [firstLaunch, setFirstLaunch] = useState(null);

  useEffect(() => {
    controlFirstLaunch();
    getAuthentication();
  }, [authenticated, fisrtLaunch]);

  const controlFirstLaunch = async () => {
    let data = await firstTimeLaunch();
    setFirstLaunch(data);
  };

  const getAuthentication = async () => {
    let auth = await isAuthenticated();
    // console.log(auth);
    setAuthenticated(auth);
  };
  if (firstLaunch) {
    return <Redirect href={"onBoarding"} />;
  } else if (authenticated) {
    return <Redirect href={"authStackTabs"} />;
  } else return <Redirect href={"unAuthStack"} />;
};

export default Home;

我尝试使用另一种名为 isLoading 的状态和许多其他解决方案,但没有任何效果

reactjs react-native react-hooks
1个回答
0
投票

组件渲染然后效果运行,因此

<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 {
        await Promise.all([
          controlFirstLaunch(),
          getAuthentication(),
        ]);
      } catch(error) {
        // handle/ignore any errors/rejections
      } finally {
        setIsLoading(false);
      }
    };

    loadData();
  }, [authenticated, fisrtLaunch]);

  const controlFirstLaunch = async () => {
    const data = await firstTimeLaunch();
    setFirstLaunch(data);
  };

  const getAuthentication = async () => {
    const auth = await isAuthenticated();
    setAuthenticated(auth);
  };

  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"} />;
};
© www.soinside.com 2019 - 2024. All rights reserved.