zl程序教程

您现在的位置是:首页 >  工具

当前栏目

React-router路由实践

路由React 实践 Router
2023-09-27 14:29:06 时间

首先下载react-router

npm install react-router --save
 
 
  • 1

使用时,路由器Router就是React的一个组件。

import { Router } from 'react-router';
render(<Router/>, document.getElementById('app'));
 
 
  • 1
  • 2

Router组件本身只是一个容器,真正的路由要通过Route组件定义。

import ReactDOM from 'react-dom';
import { Router, Route, hashHistory } from 'react-router';
ReactDOM.render((
    <Router history={hashHistory}>
        <Route path='/'>
            <IndexRoute component={Home}/>
            <Route path="login" component={Login}/>
            <Route path="test" component={Test}/>
            <Route path="*" component={NotFound}/>
        </Route>
    </Router>
),document.getElementById('root'));
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

上面代码中,用户访问根路由/,组件APP就会加载到document.getElementById(‘root’)。你可能还注意到,Router组件有一个参数history,它的值hashHistory表示,路由的切换由URL的hash变化决定,即URL的#部分发生变化。举例来说,用户访问http://www.example.com/,实际会看到的是http://www.example.com/#/


一、嵌套路由


Route组件还可以嵌套。

    <Router history={appHistory}>
        <Route path='/' component={Home}>
            <Route path="login" component={Login}/>
            <Route path="test" component={Test}/>
            <Route path="*" component={NotFound}/>
        </Route>
    </Router>
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

上面代码中,用户访问/login时,会先加载App组件,然后在它的内部再加载Home组件。

二、path 属性


Route组件的path属性指定路由的匹配规则。这个属性是可以省略的,这样的话,不管路径是否匹配,总是会加载指定组件。

<Route path="home" component={Home}>
   <Route path="user/:id" component={User} />
</Route>
 
 
  • 1
  • 2
  • 3

上面代码中,当用户访问/home/user/:id时,会加载下面的组件。

<Home>
  <User/>
</Home>
 
 
  • 1
  • 2
  • 3

如果省略外层Route的path参数,写成下面的样子。

<Route component={Home}>
  <Route path="home/user/:id" component={User} />
</Route>
 
 
  • 1
  • 2
  • 3

现在用户访问/home/user/:id时,组件加载还是原来的样子。

<Home>
  <User/>
</Home>
 
 
  • 1
  • 2
  • 3

三、IndexRoute 组件


<Router>
  <Route path="/" component={App}>
    <IndexRoute component={Home}/>
    <Route path="login" component={Login}/>
    <Route path="test" component={Test}/>
    <Route path="*" component={NotFound}/>
  </Route>
</Router>
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

指定默认情况下加载的子组件
现在,用户访问/的时候,加载的组件结构如下。

<App>
  <Home/>
</App>
 
 
  • 1
  • 2
  • 3

注意,IndexRoute组件没有路径参数path。

四、Redirect重定向


组件用于路由的跳转,即用户访问一个路由,会自动跳转到另一个路由。

<Route path="home" component={Home}>
  {/* 从 /home/user/:id 跳转到 /user/:id */}
  <Redirect from="user/:id" to="/user/:id" />
</Route>
 
 
  • 1
  • 2
  • 3
  • 4

现在访问/home/user/2,会自动跳转到/user/2。

五、IndexRedirect 组件


IndexRedirect组件用于访问根路由的时候,将用户重定向到某个子组件。

<Route path="/" component={App}>
  <IndexRedirect to="/welcome" />
  <Route path="welcome" component={Welcome} />
  <Route path="about" component={About} />
</Route>
 
 
  • 1
  • 2
  • 3
  • 4
  • 5

上面代码中,用户访问根路径时,将自动重定向到子组件welcome。


Link组件用于取代<a> 元素,生成一个链接,允许用户点击后跳转到另一个路由。它基本上就是<a>元素的React 版本,可以接收Router的状态。

render() {
  return <div>
    <ul role="nav">
      <li><Link to="/about">About</Link></li>
      <li><Link to="/repos">Repos</Link></li>
    </ul>
  </div>
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

如果希望当前的路由与其他路由有不同样式,这时可以使用Link组件的activeStyle属性。

<Link to="/about" activeStyle={{color: 'red'}}>About</Link>
<Link to="/repos" activeStyle={{color: 'red'}}>Repos</Link>
 
 
  • 1
  • 2

上面代码中,当前页面的链接会红色显示。 
另一种做法是,使用activeClassName指定当前路由的Class。

<Link to="/about" activeClassName="active">About</Link>
<Link to="/repos" activeClassName="active">Repos</Link>
 
 
  • 1
  • 2

上面代码中,当前页面的链接的class会包含active。 
在Router组件之外,导航到路由页面,可以使用浏览器的History API,像下面这样写。

import { browserHistory } from 'react-router';
browserHistory.push('/some/path');
 
 
  • 1
  • 2

七、histroy 属性


Router组件的history属性,用来监听浏览器地址栏的变化,并将URL解析成一个地址对象,供 React Router 匹配。 
history属性,一共可以设置三种值。

browserHistory 
hashHistory 
createMemoryHistory

如果设为hashHistory,路由将通过URL的hash部分(#)切换,URL的形式类似example.com/#/some/path。

import { hashHistory } from 'react-router'
render(
  <Router history={hashHistory} routes={routes} />,
  document.getElementById('app')
)
 
 
  • 1
  • 2
  • 3
  • 4
  • 5


如果设为browserHistory,浏览器的路由就不再通过Hash完成了,而显示正常的路径example.com/some/path,背后调用的是浏览器的History API。

import { browserHistory } from 'react-router'
render(
  <Router history={browserHistory} routes={routes} />,
  document.getElementById('app')
)
 
 
  • 1
  • 2
  • 3
  • 4
  • 5

但是,这种情况需要对服务器改造。否则用户直接向服务器请求某个子路由,会显示网页找不到的404错误。 
如果开发服务器使用的是webpack-dev-server,加上–history-api-fallback参数就可以了。

$ webpack-dev-server –inline –content-base . –history-api-fallback 
createMemoryHistory主要用于服务器渲染。它创建一个内存中的history对象,不与浏览器URL互动。 
const history = createMemoryHistory(location) 


八、路由钩子函数


每个路由都有Enter和Leave钩子,用户进入或离开该路由时触发。

<Route path="about" component={About} />
<Route path="inbox" component={Inbox}>
  <Redirect from="messages/:id" to="/messages/:id" />
</Route>
 
 
  • 1
  • 2
  • 3
  • 4

上面的代码中,如果用户离开/messages/:id,进入/about时,会依次触发以下的钩子。

/messages/:id的onLeave 
/inbox的onLeave 
/about的onEnter

下面是一个例子,使用onEnter钩子替代组件。

<Route path="inbox" component={Inbox}>
  <Route
    path="messages/:id"
    onEnter={
      ({params}, replace) => replace(`/messages/${params.id}`)
    } 
  />
</Route>
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

下面是一个高级应用,当用户离开一个路径的时候,跳出一个提示框,要求用户确认是否离开。

const Home = withRouter(
  React.createClass({
    componentDidMount() {
      this.props.router.setRouteLeaveHook(
        this.props.route, 
        this.routerWillLeave
      )
    },

    routerWillLeave(nextLocation) {
      // 返回 false 会继续停留当前页面,
      // 否则,返回一个字符串,会显示给用户,让其自己决定
      if (!this.state.isSaved)
        return '确认要离开?';
    },
  })
)
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

上面代码中,setRouteLeaveHook方法为Leave钩子指定routerWillLeave函数。该方法如果返回false,将阻止路由的切换,否则就返回一个字符串,提示用户决定是否要切换。

九、通配符


path属性可以使用通配符。

<Route path="/hello/:name"> 
// 匹配 /hello/michael 
// 匹配 /hello/ryan

<Route path="/hello(/:name)"> 
// 匹配 /hello 
// 匹配 /hello/michael 
// 匹配 /hello/ryan

<Route path="/files/*.*"> 
// 匹配 /files/hello.jpg 
// 匹配 /files/hello.html

<Route path="/files/*"> 
// 匹配 /files/ 
// 匹配 /files/a 
// 匹配 /files/a/b

<Route path="/**/*.jpg"> 
// 匹配 /files/hello.jpg 
// 匹配 /files/path/to/file.jpg

通配符的规则如下。

(1):paramName 
:paramName匹配URL的一个部分,直到遇到下一个/、?、#为止。这个路径参数可以通过this.props.params.paramName取出。 
(2)() 
()表示URL的这个部分是可选的。 
(3)* 
*匹配任意字符,直到模式里面的下一个字符为止。匹配方式是非贪婪模式。 
(4) ** 
** 匹配任意字符,直到下一个/、?、#为止。匹配方式是贪婪模式。

path属性也可以使用相对路径(不以/开头),匹配时就会相对于父组件的路径,可以参考上一节的例子。嵌套路由如果想摆脱这个规则,可以使用绝对路由。 
路由匹配规则是从上到下执行,一旦发现匹配,就不再其余的规则了。

<Route path="/comments" ... />
<Route path="/comments" ... />
 
 
  • 1
  • 2

上面代码中,路径/comments同时匹配两个规则,第二个规则不会生效。 
设置路径参数时,需要特别小心这一点。

<Router>
  <Route path="/:userName/:id" component={UserPage}/>
  <Route path="/about/me" component={About}/>
</Router>
 
 
  • 1
  • 2
  • 3
  • 4

上面代码中,用户访问/about/me时,不会触发第二个路由规则,因为它会匹配/:userName/:id这个规则。因此,带参数的路径一般要写在路由规则的底部。 
此外,URL的查询字符串/foo?bar=baz,可以用this.props.location.query.bar获取。