我有一個物流選項卡,如果logisticData
值為null,我會將頁面重新導向到"/logistic"
from ":logisticId/edit"
但是,當我執行此程式碼時,它不會重定向程式碼
function EditLogistic() { const { state } = useLocation(); const logisticData = state; console.log(logisticData) const navigate = useNavigate(); if (!logisticData) { console.log("empty") navigate('/logistic') redirect('/logistic') } }
我想知道我是否做錯了什麼,或者是否有任何方法可以實現這一目標?
P粉3524080382024-02-26 18:29:38
redirect
實用函數僅在資料路由器的載入器和操作函數中有效,在React元件中無效。
您可以透過 useEffect
掛鉤中的 navigate
函數發出命令式導航操作:
import { useLocation, useNavigate } from 'react-router-dom'; function EditLogistic() { const { state } = useLocation(); const logisticData = state; const navigate = useNavigate(); useEffect(() => { if (!logisticData) { navigate("/logistic", { replace: true }); } }, [logisticData, navigate]); … }
或您可以透過 Navigate
元件發出聲明性#導覽操作:
import { Navigate, useLocation } from 'react-router-dom'; function EditLogistic() { const { state } = useLocation(); const logisticData = state; if (!logisticData) { return; } … }