精通react之react-router4源码分析,100代码实现router功能

1、react-router4

  是一个 react 组件

  通过和 location / histroy 结合,来显示页面不同URL对应显示不同的组件

  其中包含了三种路由。hash / boswer 等

2、react-router基本原理

  要对 history 进行解析和封装

  要对 history/location 的改变进行监听

  当 history/locaiton 改变触发 组件的路由检测

  最后对应的渲染匹配的组件

3、实现

  根据以上的分析。

  我们可以开始实现基础模型代码

  

  创建要给 Router.js 组件

  this.state = {
            children: null
  }
  // 这里是我们要渲染的子组件
  // 匹配好的组件组装后显示

  

   componentWillMount() {
        let {children} = this.props
        const {pathnpame} = window.location
        children = this.checkRouter(children, pathname)
        this.setState({
            children
        })
    }
    // 因为是模型代码
    // 所以我之写初次进入的代码
    // 在这里我们拦截 componentWillMount
    // 根据 pathnpame ,children 实现检测和匹配
    // checkRouter 匹配检测函数

  

  function checkRouter(childrens, pathname) {
            childrens.forEach((item, index) => {
                const {props, type} = item
                if (Object.prototype.toString.call(type) == '[object Function]' && type.name == 'Route') {
                    let {extra, path, children} = props
                    console.log(item)
                    if (path !== pathname && !extra) {
                        childrens[index].props.children= null
                    } else {
                        if (new RegExp(`^${path}`).test(pathname)) {
                            let {children} = props
                            if (Object.prototype.toString.call(children) == '[object Array]') {
                                childrens[index].props.children = checkRouter(children, pathname)
                            }
                        } else {
                            childrens[index].props.children= null
                        }
                    }
                } else {
                    let {children} = props
                    if (Object.prototype.toString.call(children) == '[object Array]') {
                        childrens[index].props.children = checkRouter(children, pathname)
                    }
                }

            })
            return childrens
        }

  

  // 这里是匹配具体的规则

  // 代码不多,自己理解吧

  在创建一个 route.js

  route.js 只要实现返回 子组件就 OK 了

4、调用

            <Router>
                <div>1</div>
                <Text>
                    <div>3</div>
                    <Route path='/test2'>7</Route>
                </Text>
                <Route path='/test'>4</Route>
                <Route extra path='/switch'>
                    <div>2</div>
                    <Route path='/switch/one'>5</Route>
                    <Route path='/switch/two'>
                        <div>6</div>
                    </Route>
                </Route>
            </Router>

  

5、完成

有什么问题可以留言回复哦!!!