主要分为 history 和 hash路由两种

react路由:路由跳转页面不会刷新,a标签会跳转刷新

history(在ie浏览器存在兼容性问题)
路由跳转: pushstate、replacestate 浏览器回退: popstate

hash路由 (实现主要在于hash原本用于锚点)
hashchange 监听location.hash的变化

ReactRouter

history : 负责浏览器页面,链接改变,通知当前页面location对象发生改变,开发者自己根据变化渲染内容
Router:负责监听页面对象发生了改变,并开始重新渲染当前页面;
Route 页面开始渲染后,根据具体的页面location信息展示具体路由地址对应的内容(组件)

React.render( 
  <BrowserRouter>  ==== <Router history={createHistory()} > </Router>
    <Layout> 
      <Switch> 
        <Route exact path="/msg">  
          <Message /> 
        </Route> 
        <Route exact path="/index"> 
          <Index />  
        </Route>  
        <Route exact path="/about"> 
            <About /> 
        </Route>  
        <Route path='/test/:id?/:key?' render={(props) => { console.log('111router/test', props);  return props.location.pathname;  }} /> 
        <Route path='/param/:a?/:b?' component={(props) => { return <Param {...props} />  }}></Route> 
        <Redirect from='/' to='/index' /> 
        </Switch>  
      </Layout> 
  </BrowserRouter> 
), document.body)
// Router
<RouterContext.provider 
  value={{
    history: this.props.history,
    location: this.state.location,
    match: Router.computeRootMatch(this.state.location.pathname),
    staticContext: this.props.staticContext //静态路由
  }}
 >
  <HistoryContext.provider
    children={this.props.children || null}
    value={this.props.history}
  />
 <RouterContext.provider>

// Route   Route 渲染方式 children render component
<RouterContext.Consumer>
  内部 matchPath 
param/:a/:b  param/1/2  通过pathToRegexp 解析而成{a: 1,b:2}  
</RouterContext.Consumer>

withRouter
通过withRouter 包裹后的组建可以拿到 Router上面provider 提供的数据信息, 也可以render={(prosp) => return React.cloneElement(<componet/> ,{...props})}

exact 会判断 传进来 pathname === url 是否全等 false => return null

switch
React.children.forEach(this.props.children, child => {
if(match === null )
return
})

循环遍历返回

页面链接改变history里面的pushstate => 事件监听 触发 setState, 从而触发渲染, router里面的location


小猿张
3 声望0 粉丝