[英]React Router V6 Redirection to 404 page
I'm building a React app and I would like to know how I can redirect to a 404 page if when in the onMount method of the component.我正在构建一个 React 应用程序,我想知道如何在组件的 onMount 方法中重定向到 404 页面。 I don't find any data coming from the api
我没有找到来自 api 的任何数据
I have already build the 404 page and route我已经构建了 404 页面和路由
<Route path="*" element={<NotFoundView />} />
Code:代码:
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>;
}
};
I would like to instead of returning <h1>Wrong name</h1>
redirect the user to the path "*" and not mount the page.我不想返回
<h1>Wrong name</h1>
而是将用户重定向到路径“*”并且不挂载页面。
solution 1: change:解决方案1:更改:
else {
return <h1>Wrong name</h1>;
}
to:到:
else {
return <NotFoundView />;
}
do not forget to import import NotFoundView from "<path>/NotFoundView ";
不要忘记
import NotFoundView from "<path>/NotFoundView ";
Solution 2:解决方案 2:
use the useNavigate
hook in your case:在您的案例中使用
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.