Navigation und Umleitung werden nicht auf den Pfad im React-Router umgeleitet
P粉418214279
P粉418214279 2024-02-25 19:18:43
0
1
373

Ich habe einen Logistik-Tab, wenn logisticData 值为 null,我会将页面重定向到 "/logistic" from ":logisticId/edit"

Aber wenn ich diesen Code ausführe, wird der Code nicht umgeleitet

function EditLogistic() {
  const { state } = useLocation();
  const logisticData = state;

  console.log(logisticData)

  const navigate = useNavigate();

  if (!logisticData) {
    console.log("empty")
    navigate('/logistic')
    redirect('/logistic')
  }
}

Ich frage mich, ob ich etwas falsch mache oder ob es eine Möglichkeit gibt, dies zu erreichen?

P粉418214279
P粉418214279

Antworte allen(1)
P粉352408038

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

  ...
}
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!