react BrowserRouter Route 原理实现

Context.js

import React from 'react'
const { Provider, Consumer } = React.createContext()
export { Provider, Consumer }

BrowserRouter.js

import React, { Component } from "react";
import { createBrowserHistory } from 'history'
import {Provider} from '../Context'

class BrowserRouter extends Component {
    constructor(props) {
        super(props)
        this.history = createBrowserHistory()
        this.state = {
            location: this.history.location,
        }
        this.unListen = this.history.listen(location => {
            this.setState({
                location
            })
        })
    }

    componentWillUnmount() {
        this.unListen && this.unListen()
    }
    render() {
        let value = {
            history:this.history,
            location:this.state.location
        }
        return (
            
                {this.props.children}
            
        )
    }
}
export default BrowserRouter

Route.js

import React, { Component } from 'react';
import {Consumer} from '../Context'
import pathToReg from "path-to-regexp";

class Route extends Component {
    render() {     
        return (
            
                {
                    vaule=>{
                        const {path,component:Component,exact=false}=this.props
                        let pathname=vaule.location.pathname
                        let keys=[]
                        const reg=pathToReg(path,keys,{end:exact})
                        let result=pathname.match(reg)
                        console.log(result)
                        keys=keys.map(item=>item.name)
                        let [url,...vaules]=result
                        console.log(keys)
                        let props={
                            history:vaule.history,
                            location:vaule.location,
                            match:{
                                params:keys.reduce((obj,current,index)=>{
                                    console.log(keys)
                                    obj[current]=vaules[index]
                                    console.log(obj)
                                    return obj
                                },{})
                            }

                        }
                        if(result){
                            return 
                        }else{
                            return null
                        }
                       
                    }
                }
            
         
        );
    }
}

export default Route;

你可能感兴趣的:(javascript,react.js)