假设我有这些路线:
<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 时,它会重定向未找到的页面并刷新页面。我需要在不刷新的情况下重定向。有什么解决办法吗?
最佳答案
window.location.href
刷新页面。由于您似乎正在使用 React Router Dom v5
,因此您应该使用 useHistory进行重定向。以下是您将如何使用它的概述(注意注释):
import { useHistory } from "react-router-dom";
function HomeButton() {
let history = useHistory(); // you call it at the top level of the component
function handleClick() {
history.push("/home"); // use it wherever you want
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}
与 useHistory
或重定向无关,但您可以稍微优化您的路由设置:
<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="/not-found" component={NotFound} />
<Redirect to="/not-found" />
</Switch>
对于 React Router Dom v6
,使用 useNavigate将被用来代替 useHistory .
关于javascript - 如果使用 React Router Dom 不存在 slug,如何重定向到未找到的页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72436792/