代码之家  ›  专栏  ›  技术社区  ›  noobCoder

在React Native中,SetState在初始渲染index.js时不起作用,甚至我的函数也给出了所需的输出,如true或false

  •  1
  • noobCoder  · 技术社区  · 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的状态和许多其他解决方案,但都不起作用

    1 回复  |  直到 1 年前
        1
  •  0
  •   Drew Reese    1 年前

    组件渲染 然后 效果运行,所以 <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"} />;
    };