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

1,617 阅读2分钟

1.创建react项目

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

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

cd my-app 进入项目

npm start 启动

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}==相当于路由试图的容器

4.定义路由 index.js

render

(<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>组件有如下属性:

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

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

索引 IndexRoute

指定默认情况下加载的子组件。你可以把IndexRoute想象成某个路径的index.html。

例如:

<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来加载和卸载不同的组件