美文网首页
《All About React Router 4》 笔记

《All About React Router 4》 笔记

作者: 孤丶晴 | 来源:发表于2018-01-10 13:46 被阅读278次

    原文:

    All About React Router 4

    示例代码

    All About React Router 4 笔记

    此文来自一篇英文博客,记录学习时总结的一些知识点,如有错误,请指正,谢谢!

    React Router 4 带来新的API以及新的心智模型。

    Inclusive Routing 引入路由

     const PrimaryLayout = () => (
      <div className="primary-layout">
        <header>
          Our React Router 4 App
          <Route path="/users" component={UsersMenu} />
        </header>
        <main>
          <Route path="/" exact component={HomePage} />
          <Route path="/users" component={UsersPage} />
        </main>
      </div>
    )
    
    

    UsersMenuUsersPage 可以通过同一个路由被渲染到当前页面中,

    exact 精确匹配路由 '/'

    Switch 路由组

    当你需要将路由匹配到一个路由组时,使用 Switch 可以匹配到唯一路由

    const PrimaryLayout = () => (
      <div className="primary-layout">
        <PrimaryHeader />
        <main>
          <Switch>
            <Route path="/" exact component={HomePage} />
            <Route path="/users/add" component={UserAddPage} />
            <Route path="/users" component={UsersPage} />
            <Redirect to="/" />
          </Switch>
        </main>
      </div>
    )
    

    当使用 Switch 时,只有一个路由会被渲染。

    我们仍然需要使用 exact 当设 HomePage 为首选被渲染的组件。否则等浏览到 /users 或则会使 '/users/add' 时,HomePage 组件仍然会被渲染,如果发生同时渲染,那么先渲染的组件排在最前面。

    当路由匹配 /users/add 时,也会同时匹配到 /users 路由,为确保优先渲染UserAddPage 可以将这个组件写到 UsersPage 前面,如果相反,则调换顺序。
    当然也可以将所有路由设置为 exact 精确匹配,这样就不存在先后问题。

    Redirect 重定向

    Switch 没有匹配到任意一个路由的时候,将会发生路由重定向。

    "Index Routes" and "Not Found" (已移除)

    在 V4 中不在使用 <IndexRoute>, 而是使用 <Route exact> 精确匹配路由。

    如果没有路由被匹配,可以使用 <Switch><Redirect> 去重定向到默认路由,或者重定向到 404页面

    Nested Layouts 嵌套布局

    这里展示两种不同的写法,以及为什么第二种是更好的写法

    第一种采用 exact 精确匹配路由

    const PrimaryLayout = props => {
      return (
        <div className="primary-layout">
          <PrimaryHeader />
          <main>
            <Switch>
              <Route path="/" exact component={HomePage} />
              <Route path="/users" exact component={BrowseUsersPage} />
              <Route path="/users/:userId" component={UserProfilePage} />
              <Route path="/products" exact component={BrowseProductsPage} />
              <Route path="/products/:productId" component={ProductProfilePage} />
              <Redirect to="/" />
            </Switch>
          </main>
        </div>
      )
    }
    

    这种写法在技术上是可行的,但是问题在于,props.match 是通过 <Route> 组件传递的。组件 BrowseUsersPage 的子组件并不是通过 <Route> 嵌套路路由中,子组件是不能直接拿到 props.match的。

    当然这里可以通过高阶组件的方式将子组件包装:withRouter()

    第二种写法在第一种写法的基础上做了修改,通过路由嵌套的方式布局组件,并且不再需要使用 exact 精确匹配路由,也不必使用 withRouter() 加工组件。

    const PrimaryLayout = () => (
        <div className="primary-layout">
            <PrimaryHeader />
            <main>
                <Switch>
                    <Route path="/" exact component={HomePage} />
                    <Route path="/users" component={UserSubLayout} />
                    <Route path="/products" component={ProductSubLayout} />
                    <Redirect to="/" />
                </Switch>
            </main>
        </div>
    );
    
    const UserSubLayout = () => (
        <div className="user-sub-layout">
            <aside>
                <UserNav />
            </aside>
            <div className="primary-content">
                <Switch>
                    <Route path="/users" exact component={BrowseUsersPage} />
                    <Route path="/users/:userId" component={UserProfilePage} />
                </Switch>
            </div>
        </div>
    );
    
    const UserSubLayout = props => (
        <div className="user-sub-layout">
            <aside>
                <UserNav />
            </aside>
            <div className="primary-content">
                <Switch>
                    <Route
                        path={props.match.path}
                        exact
                        component={BrowseUsersPage}
                    />
                    <Route
                        path={`${props.match.path}/:userId`}
                        component={UserProfilePage}
                    />
                </Switch>
            </div>
        </div>
    );
    

    Match 匹配对象

    Match 对象提供了一下几种属性

    • params - (object) Key/value pairs parsed from the URL corresponding to the dynamic segments of the path
    • isExact - (boolean) true if the entire URL was matched (no trailing characters)
    • path - (string) The path pattern used to match. Useful for building nested <Route>s
    • url - (string) The matched portion of the URL. Useful for building nested <Link>s

    match.path vs match.url

    当路由不携带参数是两者的输出是相同的字符串,尝试打印这两者。

    当路由匹配到例如 /users/5 时,match.url 将会输出 "/users/5" ; 而 match.path 输出 "/users/:userId".

    Avoiding Match Collisions 避免匹配冲突

    const UserSubLayout = ({ match }) => (
      <div className="user-sub-layout">
        <aside>
          <UserNav />
        </aside>
        <div className="primary-content">
          <Switch>
            <Route exact path={props.match.path} component={BrowseUsersPage} />
            <Route path={`${match.path}/add`} component={AddUserPage} />
            <Route path={`${match.path}/:userId/edit`} component={EditUserPage} />
            <Route path={`${match.path}/:userId`} component={UserProfilePage} />
          </Switch>
        </div>
      </div>
    )
    

    path-to-regexp 用于校验路由参数

    var re = pathToRegexp('/:foo(\\d+)')
    // keys = [{ name: 'foo', ... }]
    
    re.exec('/123')
    //=> ['/123', '123']
    
    re.exec('/abc')
    //=> null
    

    Authorized Route 路由认证、权限管理

    根据用户登录状态管理其浏览路由的权限是应用中很常见的功能

    with the help of v4 docs

    class App extends React.Component {
      render() {
        return (
          <Provider store={store}>
            <BrowserRouter>
              <Switch>
                <Route path="/auth" component={UnauthorizedLayout} />
                <AuthorizedRoute path="/app" component={PrimaryLayout} />
              </Switch>
            </BrowserRouter>
          </Provider>
        )
      }
    }
    

    可以结合 react redux设计权限管理功能,<AuthorizedRoute> 组件先检测当前的登录状态,
    如果是正在登录,则显示 Loading...

    如果已经登录则,则跳转到到 <PrimaryLayout> 组件中

    如果未登录,则跳转到登录页

    class AuthorizedRoute extends React.Component {
      componentWillMount() {
        getLoggedUser()
      }
    
      render() {
        const { component: Component, pending, logged, ...rest } = this.props
        return (
          <Route {...rest} render={props => {
            if (pending) return <div>Loading...</div>
            return logged
              ? <Component {...this.props} />
              : <Redirect to="/auth/login" />
          }} />
        )
      }
    }
    
    const stateToProps = ({ loggedUserState }) => ({
      pending: loggedUserState.pending,
      logged: loggedUserState.logged
    })
    
    export default connect(stateToProps)(AuthorizedRoute)
    

    Other mentions 其他

    <Link> vs <NavLink>

    这两个功能一样,都是路由跳转,但是NavLink有一个属性用来显示跳转选中的样式,activeStyle属性,写显示高亮样式的,接收一个对象{}

    在我们路由导航有一个to属性

    to属性是我们路由的要跳转的路径:

    import React from 'react'
    import { NavLink } from 'react-router-dom'
    
    const PrimaryHeader = () => (
      <header className="primary-header">
        <h1>Welcome to our app!</h1>
        <nav>
          <NavLink to="/app" exact activeClassName="active">Home</NavLink>
          <NavLink to="/app/users" activeClassName="active">Users</NavLink>
          <NavLink to="/app/products" activeClassName="active">Products</NavLink>
        </nav>
      </header>
    )
    
    export default PrimaryHeader
    

    Dynamic Routes 动态路由

    在 V4中最好的一部分改变是可以在所有地方包含 <Route> , 它只是一个 React 组件。

    路由将不再是神奇的东西,我们可以用在任何地方,试想一下,当满足条件时,整个路由都可以被路由到。

    在这些条件不满足时,我们可以移除那些路由,甚至,可以嵌套路由。

    React Router 4 变得更好用是因为这只是一个 Just Components™

    相关文章

      网友评论

          本文标题:《All About React Router 4》 笔记

          本文链接:https://www.haomeiwen.com/subject/lvlonxtx.html