react-router

297 阅读2分钟
  1. react-router原理:不同的路径渲染不同的组件,有两种实现方式
HashRouter:利用hash实现路由切换
BrowserRouter:实现h5 Api实现路由的切换

HashRouter就是根据url的哈希值来判断的
BrowserRouter就是通过history来判断的
  1. History API
window.onpopstate = function(event) {
  alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
};
// params: state title url
history.pushState({page: 1}, "title 1", "?page=1");
history.pushState({page: 2}, "title 2", "?page=2");
history.replaceState({page: 3}, "title 3", "?page=3");
history.back(); // alerts "location: http://example.com/example.html?page=1, state: {"page":1}"
history.back(); // alerts "location: http://example.com/example.html, state: null
history.go(2);  // alerts "location: http://example.com/example.html?page=3, state: {"page":3}

  1. 安装react-router: yarn add react-router-dom
  2. 路由对象
{
    "match": {
        "path": "/user/:id",   //匹配路径
        "url": "/user/1",      //地址栏中的url
        "isExact": true,       //是否精确匹配
        "params": {"id": "1"}  // 路径参数对象
    },
    "location": {
        "pathname": "/user/1",  //路径名
        "search": "?name=zfpx", //查询字符串
        "hash": "#top"          //hash"state":undefined
    },
    "history": {
        "length": 6,            //历史长度
        "action": "POP",        //动作
        "location": {           //当前应用所处的位置
            "pathname": "/user/1",
            "search": "?name=zfpx",
            "hash": "#top",
            "state":undefined  //location可以拥有与之相关的状态。这是一些固定的数据,并且不存在于URL之中
        },
        "go":f go(n),//是一个强大的方法,并包含了goForward与goBack的功能。传入负数则退后,传入正数则向前
        "goBack":f goBack(),//返回一层页面。实际上是将history的索引值减1
        "goForward":f goForward(),//与goBack相对。向前一层页面
        "listen":f listen(listener),//采用观察者模式,在location改变时,history会发出通知
        "push":f push(path,state),//方法使能你跳转到新的location
        "replace":f replace(path,state)//replace方法与push相似,但它并非添加location,而是替换当前索引上的位置,重定向时要使用replace,
        "createHref":f createHref(location)
    }
}
  1. router各个组件分析
Route  --> <Route path="/" component={Home} />
exact  --> 精准匹配 <Route path="/" exact component={Home} />
Link --> <Link to="/">home</Link>
Redirect --> <Route path="/" exact render={() => <Redirect to="/home" />} />
Switch --> 匹配到就不往下走了
withRouter --> 往组件加路由信息
NavLink --> <NavLink to="/faq" activeClassName="selected">FAQs</NavLink>
  1. 路由配置
  <Router>
    <div>
      <Route path="/">
        <Layout>
          <Switch>
            <Route path="/user" component={User}></Route>
            <Route path="/" component={Home}></Route>
          </Switch>
        </Layout>
      </Route>
    </div>
  </Router>
  1. 按需加载
import React from 'react'

export default loadComponent => (
    class AsyncComponent extends React.Component {
        state = {
            Component: null,
        }
        async componentDidMount() {
            if (this.state.Component !== null) return
            try {
                const {default: Component} = await loadComponent()
                this.setState({ Component })
            }catch (err) {
                console.error(`Cannot load component in <AsyncComponent />`);
                throw err
            }
            NProgress.done()
        }

        render() {
            const { Component } = this.state
            return (Component) ? <Component {...this.props} /> : null
        }
    }
)