【问题标题】:what is difference between useNavigate and redirect in react-route v6?react-route v6 中的 useNavigate 和 redirect 有什么区别?
【发布时间】:2022-12-13 21:17:40
【问题描述】:

我正在尝试使用 react-router v6 在 react 中构建我的身份验证逻辑 当我运行下面的代码时,我发现了一些奇怪的事情是我的代码

import React from 'react';
import useStore from '../../../store/store';
import { useEffect } from 'react';
import {useNavigate,redirect } from 'react-router-dom';


export default function (SpecificComponent, option, adminRoute = null) {

    const navigate = useNavigate();
    const {auth,accessToken}= useStore();
// option = null // pages taht anyone can access
// option = true // pages that only loginuser can access
// option = false // pages that loginuser can not access
// option = true ,adiminRoute = true // pages that only admin can access
function AuthenticationCheck(props){

    useEffect(()=>{
        auth(accessToken).then(res => {
            
            if (res.accessToken) {
             
            setAccessToken(res.accessToken)
             
            }
        //when authentication failed
        if (res.isAuth===false) {
            if (option) {
                //to sign in page
                navigate('/signin')
            }
            //when authentication successed
        } else { 
            //trying to get in admin page but user is not admin 
            if (adminRoute && res.role !== "Admin") {
                navigate('/landingpage')
                //trying to get in admin page and user is  admin  
            } else if (adminRoute && res.role === "Admin") {
                navigate('/admin')
            } else { 
                //trying to get in login page but user is signed in already
                if (option === false) {navigate('/landing')}
                
            }

        }
        //passed above, go to SpecificComponent
    });

},[])
return(
    <SpecificComponent {...props}  />
 )
  }


  return AuthenticationCheck
}

当我运行此代码并尝试以管理员用户身份进入管理页面时,我可以进入管理页面但它陷入循环并一遍又一遍地重新呈现管理页面。

else if (adminRoute && res.role === "Admin") {
            navigate('/admin')
        } 

所以我用另一个 react-router 方法 redirect 改变了导航,它工作得很好。 但是,我仍然不明白为什么导航不起作用但重定向起作用了?

这是重定向

        export declare const redirect: RedirectFunction;
/**
 * @private
 * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies
 */

这是 useNavigate

    export declare function useNavigate(): NavigateFunction;
/**
 * Returns the context (if provided) for the child route at this level of the route
 * hierarchy.
 * @see https://reactrouter.com/docs/en/v6/hooks/use-outlet-context
 */

P.S 现在,我明白了它会进入管理页面,即使我像下面那样做了我的代码,但仍然不确定为什么 useNavigate 会陷入无限循环,这就是我想知道的

else if (adminRoute && res.role === "Admin") {
                    
                }

感谢阅读,您的帮助将不胜感激

【问题讨论】:

    标签: reactjs react-router react-router-dom


    【解决方案1】:

    根据我对文档的理解和阅读,redirect 用于操作和加载程序。

    useNavigate 是一个钩子,只能在 React Hooks 和 React Components 中使用。

    因此,例如,您可以使用 useNavigate 在您的主页组件中重定向用户,例如在某些状态更改中。

    import { useNavigate } from "react-router-dom";
    import { useEffect, useState } from "react";
    
    export const Homepage = () => {
      const [shouldRedirect, setShouldRedirect] = useState(false);
      const navigate = useNavigate();
    
      useEffect(() => {
        if (shouldRedirect) navigate("/profile");
      }, [shouldRedirect]);
    
      return (
        <div>
          <button onClick={() => setShouldRedirect(true)}>Redirect</button>
        </div>
      );
    };
    

    redirect 应该用在正常的函数中,比如加载器和动作,引用 example from the docs

    import { redirect } from "react-router-dom";
    
    const loader = async () => {
      const user = await getUser();
      if (!user) {
        return redirect("/login");
      }
    };
    

    资源:

    【讨论】:

      猜你喜欢
      • 2023-02-06
      • 2021-11-10
      • 2021-02-21
      • 2017-11-24
      • 1970-01-01
      • 2022-12-10
      • 2022-01-06
      • 2022-12-25
      • 2022-08-23
      相关资源
      最近更新 更多