Navigation and redirection not redirecting to path in react router
P粉418214279
P粉418214279 2024-02-25 19:18:43
0
1
442

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粉418214279
P粉418214279

reply all(1)
P粉352408038

redirectUtility 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 ;
  }

  ...
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template