-
版本信息
首先记录一下react的版本,以及相关软件的版本信息
{
"name": "react15.6.1",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^15.6.1",
"react-dom": "^15.6.1",
"react-router": "^4.2.0",
"react-scripts": "1.0.13"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"devDependencies": {
"react-router": "^4.2.0",
"react-router-dom": "^4.2.2"
}
}
-
路由信息
看到哪里记录到哪里。首先我们 看react-router,一个前端框架语言的基本语法学习完毕,第一想看的就是该框架的路由是如何实现了。根据官网了解,react的路由目前有2.*版本和4.*版本,这两者之间有着很大的不同。今天学习的是4.2.0版本。
这个版本目前的参考文档如下http://blog.csdn.net/sinat_17775997/article/details/70155252
https://reacttraining.com/react-router/web/api/Route/Route-render-methods
路由的实现方式:
4.0的路由第一个不同在于,路由的引用,不是存在于react-router中,而是需要从react-router-dom中引入,
- 因此第一步需要安装改组件
npm install react-router-dom
- 第二步引入组件路由。目前看到的路由有多中形式
BrowserRouter ,HashRouter,Router等等
- Route元素的解析有三种定义改元素的方法
Route Compent,这种方法,就是让该路由跳转到一个新的组件,展示改组件的相关内容,这种是我常用的方法。
<Route path="/user/:username" component={User}/>
- 当我看到这个path的时候,我就想如何在User中获取到这个username呢?
我的请求路径是http://localhost:3000/user/my name react router
此时此刻我们可以自信的获取到这个username
{this.props.match.params.username} 正确
{this.props.username} 错误
- 当我的路由配置成下面的时候,是否也可以按照上面的方法获取到参数呢
<Route exact path="/user/:username" component={App}/>
很遗憾的告诉你,这样就可以了。因为此时此刻我们看到一个路由匹配的限制条件exact,就是这个关键词,让我们以失败告终。
那他到底是什么东西呢
exact: bool
当他的值为true的时候,我们是要精确匹配的,当时false的时候是模糊匹配的。
请求路径是: http://localhost:3000/user/ 路由配置是: <Route exact={false} path="/user/:username" component={App}/> 一无所有 |
请求路径是: http://localhost:3000/user/ 路由配置是: <Route exact={true} path="/user/:username" component={App}/> 一无所有 |
以上两条案例说明,配置了具有参数的path,就必须传递参数,否则无法请求到页面 |
请求路径是: http://localhost:3000/user/daf 路由配置是: <Route exact={true} path="/user/:username" component={App}/> 可以返回页面,可以获取到参数 |
请求路径是: http://localhost:3000/user/daf 路由配置是: <Route exact={false} path="/user/:username" component={App}/> 可以返回页面,可以获取到参数 |
这两条案例说明,配置了具有参数的path,只要传递参数,就可以获取到参数,当然路径只能是和配置的path一一对应。 即path为aaa/:dafa,那么请求路径也必须是bashurl/aaa/[params] |
请求路径是: http://localhost:3000/user/daf/adfasf 路由配置是: <Route exact={false} path="/user/:username" component={App}/> 可以返回页面,可以获取到参数 |
请求路径是: http://localhost:3000/user/daf/adfasf 路由配置是: <Route exact={true} path="/user/:username" component={App}/> 一无所有 |
这两条案例说明,配置了具有参数的path,如果exact为true的时候,要求路径是精确匹配,否则无法获取到该路由的地址,这也说明精确匹配路径,会认为参数不作为路径的一部分。 |
Route render,这种方法的作用,就是在定义该路由的时候返回一个字定义的组件形式
<Route path="/home" render={() => <div>Home</div>}/>
Route children ,看到线面的路由我就想到了他的作用,应该建立一个动态的字路由
<Route path={to} children={({ match }) => (
<li className={match ? 'active' : ''}>
<Link to={to} {...rest}/>
</li>
)}/>