react-router入门和初步配置

react-router-dom 的坑

Router

引入

最常见的用例使用低级<路由器>是同步一个自定义的历史状态管理自由像回家的或Mobx。注意,这是不需要使用状态管理库与路由器的反应,只有深度集成。

import { Router, Route, Link } from  'react-router-dom'
import createBrowserHistory from 'history/createBrowserHistory'

const history = createBrowserHistory()


  

4.0版本之前 更多是如下应用 发现运行错误


正确的是

import createBrowserHistory from 'history/createBrowserHistory';

const history = createBrowserHistory()

console.log(history)

history 是个对象数据

是个用于浏览器导航#的历史对象

import createBrowserHistory from 'history/createBrowserHistory'

const customHistory = createBrowserHistory()

history(path, state) //第一个参数是url 第二个是参数

Route

引入

{this.props.children}
import { BrowserRouter as Router, Route } from 'react-router-dom'


  
    
    
  

github项目的例子
https://github.com/liupeijun/react-router-v4-maizuo

const router = (
      
        
           {/*Renders the first child  or  that matches the location.*/}
          
          
            
              {/*Renders the first child  or  that matches the location.*/}
                 
                 
                  {/*重定向*/}
              
            
          }>
          
          
          
          
          
          
          
          
              
          }>
          
           {/*重定向*/}
          
        
      
    )

hashHisroy

在4.0中 url如果要出现# hash哈希的话
此方法可能不行,小伙伴可自行实践

import HashRouter from 'react-reoter-dom'


ReactDOM.render((
     //router换成HashRouter url:localhost:3000/#/
        
            
            
            
            
            
            
        
    
    ), document.getElementById('root'));

router 4.0 路由跳转方式

第一种 Link跳转

import {Link} from  'react-router-dom';

homer

这办法比较笨,灵活性不高

第二种跳转方式

4.0版本之前 更多是如下应用 发现运行错误


正确的是

import createBrowserHistory from 'history/createBrowserHistory';

const history = createBrowserHistory()

console.log(history)
goNav(path) {
    history.push('/'+ path)
}

router router-dom区别

React Router 4.0 (以下简称 RR4) 已经正式发布,它遵循react的设计理念,即万物皆组件。所以 RR4 只是一堆 提供了导航功能的组件(还有若干对象和方法),具有声明式(引入即用),可组合性的特点。github:https://github.com/ReactTraining/react-router

RR4 本次采用单代码仓库模型架构(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 静态路由配置的小助手

react-router 还是 react-router-dom?

在 React 的使用中,我们一般要引入两个包,react 和 react-dom,那么
react-routerreact-router-dom 是不是两个都要引用呢?
非也,坑就在这里。他们两个只要引用一个就行了,不同之处就是后者比前者多出了 这样的 DOM 类组件。
因此我们只需引用 react-router-dom 这个包就行了。当然,如果搭配 redux ,你还需要使用 react-router-redux。
what is the diff between react-router-dom & react-router?

但是大致还是相同的,很多办法都是可以互相用的

你可能感兴趣的:(react-router入门和初步配置)