【问题标题】:React Router redirect when url isn't correct当 url 不正确时 React Router 重定向
【发布时间】:2019-08-07 11:24:49
【问题描述】:

你能帮帮我吗!

我被 url 参数卡住了。当我输入 http://localhost:3000/#/willmatch/sdf 时,我被重定向了。太好了,这就是我想要的。但是当 http://localhost:3000/#/willmatch111/ 时,什么都没有发生。

当 url 不正确时是否可以重定向?

我尝试输入 http://localhost:3000/#/willmatch1 ,但我仍然使用 WillMatch,但如果 url 不正确,我想获取 NoMatch

import React, { Component } from 'react';
import { HashRouter as Router, Switch, Route, Link, Redirect } from 'react-router-dom';

class App extends Component {
  render() {
    return (
      <Router>
        <div>
          <ul>
            <li><Link to="/">Home</Link></li>
            <li><Link to="/willmatch">Will Match</Link></li>
            <li><Link to="/will-not-match">Will Not Match</Link></li>
            <li><Link to="/also/will/not/match">Also Will Not Match</Link></li>
          </ul>

          <Switch>
            <Route path="/" exact component={Home} />
            <Route exact path="/:id" component={WillMatch} />
            {/* <Route component={NoMatch} /> */}
            <Redirect to="/" />
          </Switch>
        </div>
      </Router>
    );
  }
}

function Home() {
  return <h1>Home</h1>
}

function WillMatch({ match }) {
  return <h1>{match.params.id}</h1>
}

function NoMatch() {
  return <h1>NoMatch}</h1>
}

export default App;

【问题讨论】:

标签: reactjs react-router


【解决方案1】:

试试&lt;Route exact strict path="/:id" component={WillMatch} /&gt;

/:id 是一个占位符,它匹配所有内容。如果没有strict,它将匹配/whatever/whatever/。对于strict,它只匹配/whatever

您要么需要列出所有有效路径,要么检查props.match.params.id 内的WillMatch 组件,如果无效则重定向。

【讨论】:

  • 我尝试输入 localhost:3000/#/willmatch1 ,但我仍然使用 WillMatch,但如果 url 不正确,我想获取 NoMatch
  • 谢谢!类似的东西?函数 WillMatch({ match }) { if (match.params.id == 'willmatch') { return

    {match.params.id}

    } else { return ; } } 我不擅长 react 语法)
【解决方案2】:

您应该能够在您的路线底部放置这样的东西,确保它位于底部,否则它将匹配每条路线。如果在其余路由中找不到路由,它将重定向!

【讨论】:

【解决方案3】:

看起来它认为它可能认为willmatch:id。我有一个这样的工作:

<Switch>
    <Route path="/" exact component={Home} />
    <Route path="/:id" component={WillMatch} />
    <Route path="/notfound" exact component={NoMatch} />
    <Redirect to="/notfound" />
</Switch>

你也可以试试:

    <Route path="/thing/:id" component={WillMatch} />

这里提供了一个类似的例子:

https://reacttraining.com/react-router/web/example/no-match

&lt;Switch&gt; 呈现第一个匹配的子 &lt;Route&gt;。没有路径的&lt;Route&gt; 始终匹配

【讨论】:

猜你喜欢
  • 2023-02-19
  • 2017-11-14
  • 2017-02-20
  • 2018-09-25
  • 2018-12-14
  • 2017-12-11
  • 2015-09-14
  • 2016-06-16
  • 1970-01-01
相关资源
最近更新 更多