【发布时间】:2022-08-08 14:31:47
【问题描述】:
假设我有这些路线:
<Switch>
<Route exact path=\"/myflix/:slug\" component={Home} />
<Route exact path=\"/myflix/:slug/register\" component={Signup} />
<Route exact path=\"/myflix/:slug/event\" component={Event} />
<Route exact path=\"/myflix/:slug/contact\" component={Contact} />
<Route exact path=\"/myflix/:slug/login\" component={Login} />
<Route exact path=\"/myflix/:slug/show-details\" component={ShowList} />
<Route exact path=\"/myflix/:slug/*\" component={NotFound} />
<Route path=\"*\" exact={true} component={NotFound} />
<Redirect to=\"/not-found\" />
{/* <Route path=\"*\" element={<NotFound />} /> */}
</Switch>
我们有来自 API 的某些 slug,形式如下:
[
{
id: 1,
title: \"_flix\",
slug: \"_flix\",
status: true,
viewTime: null,
langue: null,
createdAt: \"2021-06-24\",
updatedAt: null,
},
{
id: 9,
title: \"test_flix\",
slug: \"test_flix\",
status: true,
viewTime: null,
langue: null,
createdAt: \"2021-06-24\",
updatedAt: null,
},
{
id: 10,
title: \"flix_2\",
slug: \"flix_2\",
status: true,
viewTime: null,
langue: null,
createdAt: \"2021-06-24\",
updatedAt: null,
},
]
当我制作无效的 slug 时,我想重定向到 NotFound 页面:
useEffect(() => {
getSlug(slug)
.then((res) => {
const { id } = res.data;
document.title = res.data.title;
getSetting(id).then((result) => {
setStyle(result.data);
getLangue(id).then((res) => {
setlang(res.data.langue);
});
});
})
.catch((error) => (window.location.href = \"/not-found\"));
}, [slug]);
我使用了上面的代码(参见.catch),但是当我创建一个无效的 slug 时,它会重定向未找到的页面并刷新页面。我需要重定向而不刷新。有什么解决办法吗?
-
正如下面的答案所示,我们不会在 React 中直接使用
window或document。
标签: javascript reactjs react-router react-router-dom