javascript - 如果使用 React Router Dom 不存在 slug,如何重定向到未找到的页面?

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

假设我有这些路线:

<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/

相关文章:

javascript - 从另一个JS库加载JS库,并让页面使用它

reactjs - 如何通过semantic-ui-react为react实现分页

javascript - Graphql,react-apollo 如何在加载组件状态时将变量传递给查询

javascript - 后续调用 reloadData() 时, Angular 数据表有效负载格式不会更改

javascript - 使用 key 及其后缀从对象创建数组

javascript - 如果文本超过 10 个字母,则显示更多/更少选项

javascript - ReactJS 错误你可能需要一个合适的加载器来处理这个文件类型

javascript - 将 React 工具提示与样式化的组件一起使用

api - 使用 React Native 获取多个 API 请求

reactjs - 在 React Router v4 中突出显示默认链接