React 路由&脚手架(低版本配置)

1.建立react项目

npm install -g create-react-app 全局环境html

create-react-app my-app 建立项目react

cd my-app 进入项目ios

npm start 启动npm

React-router介绍

什么是路由?


路由是根据不一样的 url 地址展现不一样的内容或页面。
复制代码

React Router

一个针对React而设计的路由解决方案、能够友好的帮你解决React components 到URl之间的同步映射关系。
复制代码

卸载高版本react react-dom

npm uninstall react react-dom --save-dev
复制代码

安装低版本react-router

npm i react@15 react-dom@15 react-router@2  axios --save-dev
复制代码

2.准备React组件

import React from 'react'
 import ReactDOM from 'react-dom'
 import { Router, Route, Link, hashHistory} from 'react-router'
复制代码
react-router中定义了history这个属性 用于方便管理路由的方向 browserHistory/ hashHistory

3.link

定义连接的组件,相似于a标签。 <Link to='/users'>users</Link>编程

{this.props.children}==至关于路由试图的容器axios

4.定义路由 index.js

renderbash

(<Router history={hashHistory}>
		<Route path=”/" component={Demo}> <Route path="/home" component={Header}></Route> <Route path="/about" component={Con}></Route> </Route> </Router>, document.getElementById('root')) 复制代码

<Route>组件有以下属性:react-router

path(string): 路由匹配路径。(没有path属性的Route 老是会 匹配);

Component==设置该路径要加载的组件

索引 IndexRoute

指定默认状况下加载的子组件。你能够把IndexRoute想象成某个路径的index.html。app

例如:dom

<Route path="/" component={App}>
	<IndexRoute component={Index}/>
</Route>
复制代码

样式

当路径匹配时会触发activeStyle属性。
const ACTIVE = { color: 'red' }
复制代码
普通连接
<Link      to="/users"      activeStyle={ACTIVE}>users</Link>
复制代码

地址栏传参

定义:
<Link      to=“/users/1>users</Link>

<Route path="/user/:xxxx" component={User}/>
复制代码
取得参数:

this.props.params.xxxx==1

路径跳转(编程式路由)

在事件中进行路由路径跳转

hashHistory.push('/home')

绝对路径和重定向

相对路径:

不以/开头的路径,匹配时就会相对于父组件的路径。
<Route path="inbox" component={Inbox}>
   <Route path="messages/:id" component={Message} />
</Route>
复制代码
访问路径:/inbox/messages/:id

绝对路径:

以/开头的路径。若是在嵌套路由中使用会跳出父组件的影响。
<Route path="inbox" component={Inbox}>
   <Route path=“/messages/:id" component={Message} /> </Route> 复制代码
访问路径:/messages/:id

重定向:

当路径匹配from的时候,自动重定向(跳转)到to的地址上面。
<Route path=”/index" component={index}> <Redirect from=”/index/a" to=“/other" /> </Route> 复制代码

从 /index/a 跳转到 /other

重定向

<IndexRedirect to="/home"/>
复制代码

查询符-query 定义:

<Route path="/user/:xxxx" component={User}/>
复制代码

取得参数: this.props.params.xxxx

例如:

<Link to={{pathname:'/list',query:{id:item.goodsID} }}>
<Route path="/user" component={User}/>
复制代码
url:/user/10086?foo=bar


this.props.params.userId 是 10086
this.props.location.query.foo 是 bar
复制代码

总结:

路由的各个组件的生命周期和普通的组件生命周期是同样的。路由根据不一样的url来加载和卸载不一样的组件
相关文章
相关标签/搜索