美文网首页web前端开发
React-router4使用教程

React-router4使用教程

作者: 阿尔法乀 | 来源:发表于2018-12-06 19:12 被阅读0次

此教程基于React Router 4.0

React-router和React-router-dom的选择

很多刚使用react的同学在接触到react-router的时候就会很蛋疼,什么react-router和react-router-dom?往往开始会比较懵逼。下面我们就来一探究竟。
React-router
React-router提供了一些router的核心api,包括Router, Route, Switch等,但是它没有提供dom操作进行跳转的api。
React-router-dom
React-router-dom提供了BrowserRouter, Route, Link等api,我们可以通过dom的事件控制路由。例如点击一个按钮进行跳转,大多数情况下我们是这种情况,所以在开发过程中,我们更多是使用React-router-dom。安装很简单npm i react-router-dom --save,安装了淘宝镜像的就用cnpm吧。

React Router 中文文档 貌似不是最新的版本
React Router 英文文文档

核心API

1.BrowserRouter
2.HashRouter
3.Route
4.Link
5.NavLink
6.MemoryRouter
7.Redirect
8.exact
9.Switch
10.withRouter
官方文档解释很详细,我就没必要在new一次了,可以到官网学习具体用法。

功能模块

1.路由跳转

<HashRouter>
    <App>
       <Switch>
           <Route exact path="/" component={Home} />
           <Route path="/about" component={About} />
           <Route path="/contact" component={Contact} />
       </Switch>
     </App>
</HashRouter>
App组件
import React, { Component } from 'react'
export default class App extends Component {
    render() {
        return (
            <div>
                {this.props.children}
            </div>
        )
    }
}
http://localhost:3000/#/,显示Home组件内容
http://localhost:3000/#/about,显示About组件内容
http://localhost:3000/#/contact,显示Contact组件内容

2.路由传参和获取
方法一:通过params
优点:简单快捷,并且,在刷新页面的时候,参数不会丢失。
缺点:只能传字符串,并且,如果传的值太多的话,url会变得长而丑陋。
如果,你想传对象的话,可以用JSON.stringify(),想将其转为字符串,然后另外的页面接收后,用JSON.parse()转回去。

**设置路由**
<Route path="/about/:id" component={About} />
**访问方式**
<Link to={'/about/' + '2' }>About</Link>或者
this.props.history.push('/about/'+'2')
**about页面获取参数**
componentDidMount(){
    console.log(this.props.match.params.id);
}

方法二:通过query
优点:优雅,可传对象
缺点:刷新页面,参数丢失

**访问方式**
<Link to={{pathname:'/contact',query:{id:'456'}}}>contact</Link>或者
this.props.history.push({pathname :'/contact',query :{id:'456'}})
**contact页面获取参数**
componentDidMount(){
   console.log(this.props.location.query.id);
}

方法三:通过state
优点:优雅,可传对象
缺点:刷新页面,参数丢失

**访问方式**
<Link to={{pathname:'/contact',query:{id:'456'}}}>contact</Link>或者
this.props.history.push({pathname :'/contact',query :{id:'456'}})
**contact页面获取参数**
componentDidMount(){
   console.log(this.props.location.state.id);
}

备注:如果想要http://localhost:3000/#/contact?sort=name&type=1这种形式传参

this.props.history.push({pathname :'/contact',search:'?sort=name&type=1',query :{id:'456'}})
**contact页面获取参数**
this.props.location.search取参数,然后在进行解析

3.路由重定向与404

重定向:<Route exact path="/" render={() => (<Redirect to="/home"/>)}/>
<Route component={NoMatch}/>
路由指定的所有路径没有匹配时,就会加载这个NoMatch组件,也就是404页面

4.嵌套路由
写法一:

<Route path="/home" render={() =>
     <App>
         <Route path="/home/second" component={Second} />
    </App>
}/>

推荐写法

在对应组件添加<Route path='/home/second' component={Second}/>

5.权限判断
做管理后台或者是其他项目,可能有部分页面需要登录才能访问,这就需要判断有没有登录


const isAuthenticated = false;  //判断登录
function PrivateRoute({ component: Component, ...rest }) {
    return (
        <Route {...rest} render={
            props => isAuthenticated ? (<Component {...props} />) : (<Redirect to={{pathname: "/home"}}/>)
        }/>
    );
}

export default class router extends Component {
    render() {
        return (
            <HashRouter>
                <App>
                    <Switch>
                        <Route exact path="/" render={() => (<Redirect to="/home"/>)}/>
                        <Route path="/home" component={Home}/>
                        <Route path="/about/:id" component={About} />
                        <PrivateRoute path="/contact" component={Contact} />  
                        <Route component={NoMatch} />
                    </Switch>
                </App>
            </HashRouter>
        )
    }
}

6.按需加载

网络的一个重要特点是我们不必让访问者在使用它之前下载整个应用程序。您可以将代码拆分视为逐步下载应用程序。要做到这一点,我们将使用的WebPack@babel/plugin-syntax-dynamic-importreact-loadable

安装:

npm i -D babel-plugin-syntax-dynamic-import
npm i -S react-loadable

实现按需加载核心代码如下:


image.png

7.路由切换动画
react-transition-group

教程相关代码已上传github,如果帮助到你了麻烦点个star
react-router-demo

相关文章

  • React-router4使用教程

    此教程基于React Router 4.0 React-router和React-router-dom的选择 很多...

  • react-router4代码分割

    react-router4代码分割 react-router4官方文档: https://reacttrainin...

  • react-code_split

    初始化工程目录 创建async-component.js 引用component 可以结合react-router4使用

  • react-router4按需加载踩坑,填坑

    react-router4如何去实现按需加载Component,在router4以前,我们是使用getCompon...

  • react-router4升级

    react-router4升级 react-router4 跟 redux 搭配,非路由组件,就是非直接匹配的 路...

  • react-router4 modal与动态路由的冲突

    项目使用了1,react-router4,2,Bundle 动态加载路由问题:页面路由使用了动态路由,要实现一个m...

  • 未看文章

    react-router4文档react-router4文档 # react-router 按需加载2.# 浅谈R...

  • Xshell和putty使用教程

    Xshell和putty使用教程 Xshell使用教程 putty使用教程 Xshell使用教程 Xshell个人...

  • Github

    Github使用教程一Github使用教程二Github使用教程三 Git常用命令Git之使用GitHub搭建远程仓库

  • gulp 使用教程

    【gulp 使用教程】 【gulp 使用教程】一、温馨提示1.1 使用此教程前需自身已经熟悉 node 以及 np...

网友评论

    本文标题:React-router4使用教程

    本文链接:https://www.haomeiwen.com/subject/hhiwcqtx.html