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

bjg7j2ky  于 2023-04-10  发布在  Java
关注(0)|答案(2)|浏览(99)

假设我有这些路由:

<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时,它会重定向找不到的页面并刷新页面。我需要重定向而不刷新。有什么解决方案吗?

nbysray5

nbysray51#

问题

使用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>
0mkxixxg

0mkxixxg2#

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路由器Dom v6,使用useNavigate代替useHistory

相关问题