繁体   English   中英

React Router V6 重定向到 404 页面

[英]React Router V6 Redirection to 404 page

我正在构建一个 React 应用程序,我想知道如何在组件的 onMount 方法中重定向到 404 页面。 我没有找到来自 api 的任何数据

我已经构建了 404 页面和路由

<Route path="*" element={<NotFoundView />} />

代码:

  const getExercice = async () => {
    try {
      const response = await http.get(`/exercicePost/${id}`);
      if (response.status !== 400) {
        setExercice(response);
      }
    } catch {}
  };

  useEffect(() => {
    if (id !== undefined) {
      setTitle(id.replaceAll("-", " "));
      setTitleSplit(id.split("-"));
    }
    getExercice();
  }, [""]);

  if (exercice !== undefined) {
    return (
      <div className="main-container single-exercice">
        <div className="single-exercice-go-back grid grid-cols-3 ">
          <ButtonGoBack text="retour" link="../" />
        </div>
        <div className=" md:grid  md:grid-cols-3 gap-4">
          <div className="single-exercice-title">
            <span className="single-exercice-title-transparent">Exercice</span>
            {titlesplit.map((element: string, id: number) => (
              <span className="single-exercice-title-full" key={id}>
                {element}
              </span>
            ))}
          </div>

          <ImageWrapper imgUrl="d" alt="d" />
        </div>
        <div className="single-exercice-description">
          <PartFrame title="Description" />
          <p>{exercice.description}</p>
        </div>

        <div className="single-exercice-how-to">
          <PartFrame title={"Comment faire le " + title} />
          <TextList list={exercice.howToRealise} />
        </div>
      </div>
    );
  } else {
    return <h1>Wrong name</h1>;
  }
};

我不想返回<h1>Wrong name</h1>而是将用户重定向到路径“*”并且不挂载页面。

解决方案1:更改:

else {
    return <h1>Wrong name</h1>;
  }

到:

else {
    return <NotFoundView />;
  }

不要忘记import NotFoundView from "<path>/NotFoundView ";

解决方案 2:

在您的案例中使用useNavigate挂钩:

import { useNavigate } from "react-router-dom";
function Test () {
  const navigate = useNavigate();  
  if (.......) {
    return ...........;
  } else {
    return navigate("*");
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM