簡體   English   中英

如果用戶登錄,react router v6 中的 useNavigate() 以重定向到路徑

[英]useNavigate() in react router v6 to redirect to path if user is logged in

在較舊的反應版本中,如果用戶登錄,我可以使用此代碼進行重定向:

history.push('/login?redirect=shipping')

現在在 v6 中,我使用的是 useNavigate 函數而不是 history.push 但我不知道如何檢查用戶是否使用導航登錄,如果您需要更多我的代碼來回答,請告訴我,目前這是我的導航代碼:

let navigateCart = useNavigate() 

// some code here

navigateCart('/login?redirect=shipping') // the mistake is inside the parenthesis here but i dont know what it is!

這是行不通的,它帶我去.../login/shipping 而不是.../shipping

這是我的路由器配置:

<BrowserRouter>
        <Container><Routes>
            <Route path='/' element={< HomeScreen />} exact />
            <Route path='/login' element={< LoginScreen />} />
            <Route path='/profile' element={< ProfileScreen />} />
            <Route path='/shipping' element={< ShippingScreen />} />
        </Routes></Container>
</BrowserRouter>

登錄屏幕 Function:

function LoginScreen() {

    let navigateLog = useNavigate()
    let location = useLocation()

    const [email, setEmail] = useState('')
    const [password, setPassword] = useState('')

    const dispatch = useDispatch()

    const redirect = location.search ? location.search.split('=')[1] : '/'
    

    const userLogin = useSelector(state => state.userLogin)
    const { error, loading, userInfo } = userLogin


    useEffect(() => {
        if (userInfo) {
            navigateLog(redirect)
        }
    }, [navigateLog, userInfo, redirect])

    const submitHandler = (e) => {
        e.preventDefault()
        dispatch(login(email, password))
    }

LoginScreen中的useEffect中的這一行navigateLog(redirect)更改為這一行:

navigateLog(`/${redirect}`);

在您的情況下,它重定向到/login/shipping而不是/shipping ,因為就像您在調用navigateLog("shipping")因為redirect等於"shipping" ,所以它被用作相對路徑。 這意味着它考慮了您當前的 url,在您的情況下是/login

這也是您的代碼的簡化版本的工作CodeSandbox

問題

重定向目標路徑是"shipping"而不是"/shipping" react-router-dom@6中有相對路徑和絕對路徑。 區別很簡單,絕對路徑以前導"/"字符開頭,而相對路徑則沒有。 navigate("shipping")將 append "shipping"到當前pathname的末尾並導航到那里。

解決方案

在導航時添加前導"/"

navigate(`/${navigateLog}`, { replace: true });

或者在您最初導航時包含它:

navigateCart('/login?redirect=/shipping');

您可能還希望使用useSearchParams掛鈎來訪問redirect查詢參數,而不是依賴它位於特定字符串 position 處。

function LoginScreen() {
  const navigateLog = useNavigate();
  const [searchParams] = useSearchParams();

  ...

  const redirect = searchParams.get("redirect") || '/';
    
  ...

  useEffect(() => {
    if (userInfo) {
      navigateLog(redirect, { redirect: true });
    }
  }, [navigateLog, userInfo, redirect])

  ...

請注意,在發出命令式重定向時,我已經包含了一個選項 object 到指定replace: truenavigate function ,這是發出一個 REPLACE 動作而不是 PUSH 動作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM