2017-06-23 72 views
0

我想处理的情况下,用户正在写一个不存在的路径。例如 - 如果用户点击Will Not Match链接,那么NoMatch组件按预期呈现。NoMatch的反应路由器

但是,如果用户转到url并将其更改为“/ abcd”,则会向服务器发送GET请求并返回错误,因此没有使用反应路由器。我怎样才能让NoMatch组件在这种情况下呈现?

我正在使用react-router v4,顺便说一句。

import { BrowserRouter as Router, Route, Link, Switch } from 'react-router-dom' 

const NoMatch = ({ location }) => (
     <div> 
      <h3>No match for <code>{location.pathname}</code></h3> 
     </div> 
    ) 

class App extends React.Component { 
    render(){ 
     return (
      <Router> 
       <div> 
        <Link to="/page1">page1</Link> 
        <Link to="/page2">page2</Link> 
        <Link to="/will/not/match">Will Not Match</Link> 

        <Switch> 
        <Route exact path="/" component={Home}/> 
        <Route path="/page1" component={page1}/> 
        <Route path="/page2" component={page2}/> 
        <Route component={NoMatch}/> 
        </Switch> 
       </div> 
      </Router> 
     ) 
    } 
} 

回答

3

你通常需要在服务器端处理手动url写操作。没有办法(至少我不知道)在浏览器端处理这个问题。

所以基本上的想法是,在服务器端,要经常回你的应用程序不论称为URL(模数为您的API或者其他一些特殊的路由)

所以,当你的用户请求/abc

  • 服务器将返回应用程序(例如,index.html);
  • 您的浏览器将加载JS应用程序;
  • 路由器将读取该URL;
  • 将显示NoMatch组件。