我有一个物流选项卡,如果 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; } ... }