一、最基本的路由配置:
代码如下:
import React ,{Component}from 'react'; import {Router,Route,Link} from 'react-router'; class App extends Component{ render(){ return( <div> <h1>App</h1> <ul> <li><Link to="/about">About</Link></li> <li><Link to="/hello">Hello</Link></li> </ul>
{this.props.children} </div> ) } } class About extends Component{ render(){ return ( <div> <h2>About</h2> </div> ) } } class Hello extends Component{ render(){ return( <div> <h2>Hello</h2>
{this.proprs.children} </div> ) } } class Message extends Component{ render(){ return( <div> <h3>Message{this.props.params.id}</h3> </div> ) } } React.render(( <Router> <Route path="/" component={App}> <Route path="/about" component={About}/> <Route path="/hello" component={Hello}> <Route path="/message/:id" component={Message}/> </Route> </Route> </Router> ),document.body);
在上述代码中路径(URL)与组件的对应关系为:
"/" ->App,"/about"->App>About,"/hello"->App>Hello "/hello/message/:id"->App>Hello>Message
1、IndexRoute添加默认页面
上述代码中this.props.children还没有定义,此时可以用IndexRoute来设置一个默认页面。
import { IndexRoute } from 'react-router'
class Dashboard extends Component{
render() {
return <div>Welcome to the app!</div>
}
}
此时路由“/”的组件变为App>Dashboard
2、路径解耦
如果想将路径“hello/message/:id”中的hello去掉,只需要将代码:
<Route path="message/:id" component={Message}/> 改为:
<Route path="/message/:id" component={Message}/>
此时,使用绝对路径代替相对路径就可以实现。
3、兼容旧的URL
在做完第三步之后,访问"/hello/message/66"将会报错,此时我们可以使用<Redirect>,即在上述代码之下加上:
import {Redirect} from "react-router";
<Route path="/message/:id" component={Message} />
<Redirect from="message/:id" to="/message/:id" />
上述代码实际试讲“message/:id”跳转到“/message/:id”
二、路由匹配:
1、路径匹配:
:paramName匹配位于"/"、"?"或者"#"之后的URL
() 其内部的代码是可选的
* 匹配任意字符,直到下一个字符出现或者URL的末尾
三、history
react-router定义的history适用于监听浏览器地址栏的变化,主要有三种形式:browserHistory、hashHistory、createMemoryHistory。
1、browserHistory
Browser history 是使用 React Router 的应用推荐的 history。它使用浏览器中的 History API 用于处理 URL,创建一个像example.com/some/path
这样真实的 URL。代码实现如下:
import {browserHistory } from 'react-router';
<Route path="/" history={browserHistory} />
2、hashHistory
Hash history 使用 URL 中的 hash(#
)部分去创建形如 example.com/#/some/path
的路由.
3、createMemoryHistory
Memory history 不会在地址栏被操作或读取。这就解释了我们是如何实现服务器渲染的。同时它也非常适合测试和其他 的渲染环境(像 React Native )。
和另外两种history的一点不同是你必须创建它,这种方式便于测试
const history=createMemoryHistory(location)
本博客只是学习笔记,详情参见react-router的中文文档:https://react-guide.github.io/react-router-cn/