React-router 4.0之路由配置
react-router 4.0已经发布了很长一段时间了,和3.x的API相比改动了很多地方。它遵循React的设计理念,即万物皆组件。所以 RR4 只是一堆提供了导航功能的组件(还有若干对象和方法),具有声明式(声明式编程简单来讲就是你只需要关心做什么,而无需关心如何去做,好比你写 React 组件,只需要 render 出你想要的组件,至于组件是如何实现的是 React 要处理的事情。),可组合性的特点。
4.0版本本次采用单代码仓库模型架构(monorepo),这意味者这个仓库里面有若干相互独立的包,分别是:
- react-router React Router 核心
- react-router-dom 用于 DOM 绑定的 React Router
- react-router-native 用于 React Native 的 React Router
- react-router-redux React Router 和 Redux 的集成
- react-router-config 静态路由配置的小助手
看到这么多包我们就会想了,我们都需要引入吗?结果当然不是,只需要按需引入即可,在Recat中有react和react-dom两个包,我们都需要引入,但是路由只需要引入react-router-dom即可,这个包要比react-router丰富的,多出了
下面通过代码来看一下具体的实现效果:
本文例子采用的是browserRouer的方式,下面代码为APP.js
import React, { Component } from 'react';
import Index from './pages/index'
import {BrowserRouter as Router, Route} from 'react-router-dom'
import About from './pages/about'
import Inbox from './pages/inbox'
class App extends Component {
constructor(){
super();
this.state = {
myName:"1"
}
}
render() {
return (
<Router>
<div>
<div>此处可以填写整站公用html部分(如网站菜单等)</div>
<Route path="/" exact component={Index}></Route>
<Route path="/about" component={About}></Route>
<Route path="/inbox" component={Inbox}></Route>
</div>
</Router>
);
}
}
export default App;
在上面代码中,APP.js主要是起路由控制的作用,在这里配置单页面路由,不包括套用路由。如果有整站公用html部分也可以写在该组件内,或者单独写组件然后引入亦可。
路由根路径为Index组件,在进入根路径后直接显示Index组件的内容,需要在Route标签上填写exact来表示为默认路由。
再来看一下其他页面路由跳转的写法:index.js
import React,{Component} from 'react'
import {Link} from 'react-router-dom'
import logo from '../logo.svg';
import '../static/css/App.css';
export default class Index extends Component{
constructor(){
super();
}
render(){
return (
<h1>这里是about页面</h1>
<Link to="/about">about</Link>
</div>
)
}
}
在其他组件中,如果需要跳转到其他组件,只需要添加一个link标签即可,此处的link标签要跳转到的路由需要APP.js中注册。然后如果该页面需要套用路由,就需要用到下面的写法:about.js
import React,{Component} from 'react'
import Child1 from './child1'
import Child2 from './child2'
import {Link,Route,Redirect} from 'react-router-dom'
class About extends Component{
constructor(){
super();
this.state = {
myName : "这里是about页面"
}
}
componentWillMount(){
}
render(){
return (
let Child1Com = null;
if(this.props.location.pathname=='/about'){
Child1Com = <Redirect to="/about/child1">child1</Redirect>;
}else{
Child1Com = <Link to="/about/child1">child1</Link>;
}
return (
<div>
{this.state.myName}
<div>
<button onClick={this.showName.bind(this)}>按钮</button>
<Link to="/inbox">inbox</Link>
<div>
{Child1Com}
<Link to="/about/child2">child2</Link>
<Route path="/about/child1" component={Child1}/>
<Route path="/about/child2" component={Child2}/>
</div>
</div>
</div>
)
}
}
export default About
此处在about内有两个套用组件,分别为child1和child2,套用的组件需要在about组件内注册Route路由,如果希望进入后有一个默认路由,则将该路由的link修改为Redirect即可。
reac-router 4.0的简单配置暂且先说到这,后面文章会继续说明路由传参和各组件属性的问题。