Heim  >  Fragen und Antworten  >  Hauptteil

Navigation und Umleitung werden nicht auf den Pfad im React-Router umgeleitet

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粉418214279P粉418214279208 Tage vor368

Antworte allen(1)Ich werde antworten

  • P粉352408038

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

    Antwort
    0
  • StornierenAntwort