gpt4 book ai didi

reactjs - 重定向在下一个 js react 重定向之前部分显示登录页面

转载 作者:行者123 更新时间:2023-12-04 14:12:23 27 4
gpt4 key购买 nike

我有一个简单的应用程序,如果用户登录并且用户手动尝试转到/signin 页面,他将被重定向到索引页面。我正在使用 nextjs,为了实现这一点,我在 useEffect 中运行了一个函数,其中 boolean 被检查为 true 如果是这样,我使用 Router.push 用于将用户重定向到索引页面。该功能运行良好,在重定向到索引页面之前,我看到了几毫秒的登录页面。这是为什么?是不是因为每次渲染组件后都会调用useEffect?基本上我想在呈现组件之前运行该代码,并且在呈现组件之后运行 useEffect。我想基本上运行像componentWillMount这样的代码。我如何在功能组件中做到这一点?或者有其他解决方案吗?

const SigninComponent = () => {





useEffect(() => {

isAuth() && Router.push(`/`);
}, []);

return(
// components
);
}

最佳答案

那是因为 useEffect只会在组件安装后运行。
您可以使用不同的解决方案:

  • 条件渲染 , 将加载字段添加到默认情况下为 true 的状态,如果为 true,则您的组件将呈现类似微调器/加载组件的内容,如果 isAuth()返回 false 则您将呈现其他内容(很可能是登录表单)。
    伪代码 :
  • const SigninComponent = () => {
    const [loading, setLoading] = useState(true);
    useEffect(() => {
    if(isAuth()){
    Router.push(`/`);
    }else{
    setLoading(false)
    }
    }, []);

    if(!loading){
    return <Login />
    }else{
    return <MyloaderComponent />
    }
    }
  • 使用 HOC 组件 ,与上面类似,但您将上述逻辑包装在 HOC 组件中
  • 使用 getServerSideProps 并运行 isAuth()服务器端而不是客户端,如果你重定向到 getServerSideProps该组件根本不会渲染。 (您只能在页面中使用 getServerSideProps)
  • export const getServerSideProps = async (ctx) => {
    const auth = await isAuth() // or other any logic, like read cookies...

    if (!auth) {
    const { res } = ctx;
    res.setHeader("location", "/");
    res.statusCode = 302;
    res.end();
    return;
    }

    return {
    props: {}, // or return user
    };
    };

    关于reactjs - 重定向在下一个 js react 重定向之前部分显示登录页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63242809/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com