【问题标题】:How to redirect to not found page if slug doesn't exist using React Router Dom?如果使用 React Router Dom 不存在 slug,如何重定向到未找到的页面?
【发布时间】: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 中直接使用 windowdocument

标签: javascript reactjs react-router react-router-dom


【解决方案1】:

window.location.href 刷新页面。由于您似乎在使用 React Router Dom v5,因此您应该使用 useHistory 进行重定向。以下是您将如何使用它的概述(注意 cmets):

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 path="*" component={NotFound} />
</Switch>

对于 React Router Dom v6,使用 useNavigate 代替 useHistory

【讨论】:

  • 我用 This .catch((error)=>history.push("/not-found" )) 真的不刷新,但第一次正常重定向到站点,然后更改为找不到页面
  • 我刚刚编辑了您设置的路线。试试我的那个开关
  • 还有一些问题加上未找到的消息消失了,因为我认为路由器有问题
  • 我刚刚编辑了我的答案。你走的是我最后设置的路线吗?
  • 但是您没有看到NotFound 组件的内容?我编辑了我的答案,因为我第一次在路线中犯了一个错误。
【解决方案2】:

问题

使用 window.location.href = "/not-found" 会改变当前位置并重新加载页面,即它将重新安装整个 React 应用程序。使用命令式重定向到 "/not-found" 路由。

解决方案

import { useHistory } from 'react-router-dom';

...

const history = useHistory();

...

useEffect(() => {
  getSlug(slug)
    .then((res) => {
      const { id, title } = res.data;
      document.title = title;
      getSetting(id)
        .then((result) => {
          setStyle(result.data);
        });
      getLangue(id)
        .then((res) => {
          setLang(res.data.langue);
        });
    })
    .catch((error) => {
      history.replace("/not-found"); // REPLACE = redirect
    });
}, [slug]);

path="/not-found" 上渲染一个Route,可以重定向到。

<Switch>
  <Route path="/myflix/:slug/register" component={Signup} />
  <Route path="/myflix/:slug/event" component={Event} />
  <Route path="/myflix/:slug/contact" component={Contact} />
  <Route path="/myflix/:slug/login" component={Login} />
  <Route path="/myflix/:slug/show-details" component={ShowList} />
  <Redirect from="/myflix/:slug/*" to="/not-found" /> // <-- redirect unhandled paths
  <Route path="/myflix/:slug" component={Home} />
  <Route path="/not-found" component={NotFound} /> // <-- render NotFound component route
  <Redirect to="/not-found" />
</Switch>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-21
    • 2022-01-22
    • 1970-01-01
    • 2018-10-14
    • 2017-09-07
    • 1970-01-01
    • 1970-01-01
    • 2021-11-12
    相关资源
    最近更新 更多