I have a logistics tab, if the logisticData
value is null, I will redirect the page to "/logistic"
from ":logisticId/edit"
But when I execute this code it does not redirect the code
function EditLogistic() { const { state } = useLocation(); const logisticData = state; console.log(logisticData) const navigate = useNavigate(); if (!logisticData) { console.log("empty") navigate('/logistic') redirect('/logistic') } }
I'm wondering if I'm doing something wrong or if there is any way to achieve this?
P粉3524080382024-02-26 18:29:38
redirect
Utility functions are only valid in the loader and operation functions of the data router, and have no effect in React components.
You can issue imperative
navigation operations through the navigate function in the useEffect hook:
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]); ... }
Alternatively you can issue declarative navigation actions via the Navigate component:
import { Navigate, useLocation } from 'react-router-dom'; function EditLogistic() { const { state } = useLocation(); const logisticData = state; if (!logisticData) { return; } ... }