假设我有这些路由:
<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中提取了一些蛞蝓,以这种形式存在:
[
{
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时,它会重定向找不到的页面并刷新页面。我需要重定向而不刷新。有什么解决方案吗?
2条答案
按热度按时间nbysray51#
问题
使用
window.location.href = "/not-found"
改变当前位置并重新加载页面,即它将重新挂载整个React应用程序。使用命令式重定向到"/not-found"
路由。解决方案
在
path="/not-found"
上渲染一个可以重定向到的Route
。0mkxixxg2#
window.location.href
刷新页面。由于您似乎正在使用React Router Domv5
,因此您应该使用useHistory进行重定向。以下是如何使用它的概述(请注意评论):与
useHistory
或重定向无关,但您可以稍微优化路由设置:对于React路由器Dom
v6
,使用useNavigate代替useHistory。