如何在满足条件时重定向页面?

huangapple go评论125阅读模式
英文:

How to redirect a page under a condition?

问题

以下是您提供的代码的中文翻译:

我在我的项目中编写了如下的路由:

<Routes>
  <Route exact path="/" element={<Home />} />
  <Route exact path='/login' element={<Login />} />
  <Route exact path='/about' element={<About />} />
  <Route exact path='/store' element={<Store />} />
  <Route exact path='/store/:productID' element={<Product />} />
  <Route path={['/not-found', '*']} element={<NotFound />} />
</Routes>

Product 页面中,我想显示现有的产品ID并将其他产品重定向到未找到页面:

{!check && navigate("/not-found", { replace: true })}
<div className="container">
  <ul>
    <li>产品ID{productID}</li>
    <li>名称{check.name}</li>
    <li>价格{check.price}</li>
    <li><img src={check.image} /></li>
  </ul>
</div>

但我遇到了这个错误:
Uncaught TypeError: meta.relativePath.startsWith is not a function

我还使用了 navigate 组件来编写它:

{!check && <Navigate to="/not-found" />}

对于不存在的产品ID,仍然显示一个白色页面。

英文:

I wrote the Routes in my project as below:

&lt;Routes&gt;
  &lt;Route exact path=&quot;/&quot; element={&lt;Home /&gt;} /&gt;
  &lt;Route exact path=&#39;/login&#39; element={&lt;Login /&gt;} /&gt; 
  &lt;Route exact path=&#39;/about&#39; element={&lt;About /&gt;} /&gt;
  &lt;Route exact path=&#39;/store&#39; element={&lt;Store /&gt;} /&gt;
  &lt;Route exact path=&#39;/store/:productID&#39; element={&lt;Product /&gt;} /&gt;
  &lt;Route path={[&#39;/not-found&#39;, &#39;*&#39;]} element={&lt;NotFound /&gt;} /&gt; 
&lt;/Routes&gt;

In Product page I want to display the existing product ids and redirect the other ones to not-found page:

{!check &amp;&amp; navigate(&quot;/not-found&quot;, {replace: true})}
&lt;div className=&quot;container&quot;&gt;
  &lt;ul&gt;
    &lt;li&gt;Product ID: {productID}&lt;/li&gt;
    &lt;li&gt;Name: {check.name}&lt;/li&gt;
    &lt;li&gt;Price: {check.price}&lt;/li&gt;
    &lt;li&gt;&lt;img src={check.image} /&gt;&lt;/li&gt;
  &lt;/ul&gt;
&lt;/div&gt;

but I'm getting this error:
Uncaught TypeError: meta.relativePath.startsWith is not a function

I also wrote it with navigate component:

{!check &amp;&amp; &lt;Navigate to=&quot;/not-found&quot; /&gt;}

Still displays a white page for not existing ids.

答案1

得分: 2

Route 组件的 path 属性只接受字符串值,而不是数组。你需要拆分这两个路由路径。我建议在 path="/not-found" 上渲染 NotFound 组件,并将所有未处理/未知的路径重定向到它。

示例:

<Routes>
  <Route path="/" element={<Home />} />
  <Route path="/login" element={<Login />} /> 
  <Route path="/about" element={<About />} />
  <Route path="/store" element={<Store />} />
  <Route path="/store/:productID" element={<Product />} />
  <Route path="/not-found" element={<NotFound />} />
  <Route path="*" element={<Navigate to="/not-found" replace />} />
</Routes>

产品页面如果在渲染返回中尝试应用重定向逻辑,还应该渲染 Navigate 组件。

{check
  ? (
    <div className="container">
      <ul>
        <li>Product ID: {productID}</li>
        <li>Name: {check.name}</li>
        <li>Price: {check.price}</li>
        <li><img src={check.image} /></li>
      </ul>
    </div>
  )
  : <Navigate to="/not-found" replace />}

否则,navigate 函数应仅在回调或 useEffect 钩子中调用。

useEffect(() => {
  if (!check) {
    navigate("/not-found", { replace: true });
  }
}, [check]);

...

if (!check) {
  return null;
}

return (
  ...
  <div className="container">
    <ul>
      <li>Product ID: {productID}</li>
      <li>Name: {check.name}</li>
      <li>Price: {check.price}</li>
      <li><img src={check.image} /></li>
    </ul>
  </div>
  ...
);
英文:

The Route component's path prop takes only a string value, not an array. You'll need to split the two route paths up. I suggest rendering the NotFound component on path=&quot;/not-found&quot; and redirect all unhandled/unknown paths to it.

Example:

&lt;Routes&gt;
  &lt;Route path=&quot;/&quot; element={&lt;Home /&gt;} /&gt;
  &lt;Route path=&quot;/login&quot; element={&lt;Login /&gt;} /&gt; 
  &lt;Route path=&quot;/about&quot; element={&lt;About /&gt;} /&gt;
  &lt;Route path=&quot;/store&quot; element={&lt;Store /&gt;} /&gt;
  &lt;Route path=&quot;/store/:productID&quot; element={&lt;Product /&gt;} /&gt;
  &lt;Route path=&quot;/not-found&quot; element={&lt;NotFound /&gt;} /&gt;
  &lt;Route path=&quot;*&quot; element={&lt;Navigate to=&quot;/not-found&quot; replace /&gt;} /&gt;
&lt;/Routes&gt;

The product page should also render the Navigate component if you are trying to apply the redirect logic in the render return.

{check
  ? (
    &lt;div className=&quot;container&quot;&gt;
      &lt;ul&gt;
        &lt;li&gt;Product ID: {productID}&lt;/li&gt;
        &lt;li&gt;Name: {check.name}&lt;/li&gt;
        &lt;li&gt;Price: {check.price}&lt;/li&gt;
        &lt;li&gt;&lt;img src={check.image} /&gt;&lt;/li&gt;
      &lt;/ul&gt;
    &lt;/div&gt;
  )
  : &lt;Navigate to=&quot;/not-found&quot; replace /&gt;
}

Otherwise the navigate function should only be called in a callback or useEffect hook.

useEffect(() =&gt; {
  if (!check) {
    navigate(&quot;/not-found&quot;, { replace: true });
  }
}, [check]);

...

if (!check) {
  return null;
}

return (
  ...
  &lt;div className=&quot;container&quot;&gt;
    &lt;ul&gt;
      &lt;li&gt;Product ID: {productID}&lt;/li&gt;
      &lt;li&gt;Name: {check.name}&lt;/li&gt;
      &lt;li&gt;Price: {check.price}&lt;/li&gt;
      &lt;li&gt;&lt;img src={check.image} /&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/div&gt;
  ...
);

答案2

得分: 0

The 404页面显示在网站上不存在的路径上。所以,不要指定路径,使用星号(*)。

你可以像这样创建NotFound组件:

import { Link } from "react-router-dom";

export default function NotFound() {
    return (
        <div className="container">
            <ul>
                <li>Product ID:</li>
                <li>Name:</li>
                <li>Price:</li>
                <li><img src={""} /></li>
            </ul>
        </div>
    )
}

然后,你可以在主组件上为NotFound组件添加路由。

<Route path='*' element={<NotFound />} />

使用*会为所有未在路由中指定的URL渲染NotFound组件。

英文:

The 404 page displays for paths that don’t exist on the website. So, instead of specifying the path, use an asterisk (*).

You can make NotFound component like this:

import { Link } from &quot;react-router-dom&quot;;

export default function NotFound() {
    return (
        &lt;div className=&quot;container&quot;&gt;
            &lt;ul&gt;
                &lt;li&gt;Product ID:&lt;/li&gt;
                &lt;li&gt;Name:&lt;/li&gt;
                &lt;li&gt;Price:&lt;/li&gt;
                &lt;li&gt;&lt;img src={&quot;&quot;} /&gt;&lt;/li&gt;
            &lt;/ul&gt;
        &lt;/div&gt;
    )
}

And You can add Route for NotFound component on main component.

&lt;Route path=&#39;*&#39; element={&lt;NotFound /&gt;}/&gt;

Using * renders the NotFound component for all the URLs not specified in routes.

答案3

得分: 0

使用单独的路由路径/not-found,并将所有不存在的路径重定向到它。

<Routes>
  <Route path="/" element={<Home />} />
  <Route path="/login" element={<Login />} />
  <Route path="/about" element={<About />} />
  <Route path="/store" element={<Store />} />
  <Route path="/store/:productID" element={<Product />} />
  <Route path="/not-found" element={<NotFound />} />
  <Route path="*" element={<Navigate to="/not-found" replace />} />
</Routes>

并且使用Navigate组件。

if (check) {
  <div className="container">
    <ul>
      <li>Product ID: {productID}</li>
      <li>Name: {check.name}</li>
      <li>Price: {check.price}</li>
      <li><img src={check.image} /></li>
    </ul>
  </div>
}

return <Navigate to="/not-found" replace />;

根据您确定ID是否存在的方式,您还可以使用redirect()。事实上,React Router推荐在加载程序和操作中使用redirect而不是useNavigate()

在加载程序和操作中使用redirect通常比使用此钩子更好。

React Router官方文档 - use-navigate

英文:

Use a seperate route for /not-found and redirect all none-existing path to it.

&lt;Routes&gt;
  &lt;Route path=&quot;/&quot; element={&lt;Home /&gt;} /&gt;
  &lt;Route path=&quot;/login&quot; element={&lt;Login /&gt;} /&gt; 
  &lt;Route path=&quot;/about&quot; element={&lt;About /&gt;} /&gt;
  &lt;Route path=&quot;/store&quot; element={&lt;Store /&gt;} /&gt;
  &lt;Route path=&quot;/store/:productID&quot; element={&lt;Product /&gt;} /&gt;
  &lt;Route path=&quot;/not-found&quot; element={&lt;NotFound /&gt;} /&gt;
  &lt;Route path=&quot;*&quot; element={&lt;Navigate to=&quot;/not-found&quot; replace /&gt;} /&gt;
&lt;/Routes&gt;

And use the Navigate componenet.

if (check) {

    &lt;div className=&quot;container&quot;&gt;
      &lt;ul&gt;
        &lt;li&gt;Product ID: {productID}&lt;/li&gt;
        &lt;li&gt;Name: {check.name}&lt;/li&gt;
        &lt;li&gt;Price: {check.price}&lt;/li&gt;
        &lt;li&gt;&lt;img src={check.image} /&gt;&lt;/li&gt;
      &lt;/ul&gt;
    &lt;/div&gt;

}

return &lt;Navigate to=&quot;/not-found&quot; replace /&gt;

Depending on how you determine if ids exist, you can use redirect() too. In fact, react-rouer recommends using redirect instead of useNavigate()

> It's usually better to use redirect in loaders and actions than this hook
>
> https://reactrouter.com/en/main/hooks/use-navigate

huangapple
  • 本文由 发表于 2023年3月1日 15:47:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/75600824.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定