React-Router-v4 (2)实用技巧

2018-05-27  本文已影响178人  风之化身呀

1、与 v3 的差异

v3 的特点:

2、V4 的一些特性

      <Route path="/"  component={HomePage} />
      <Route path="/users" component={UsersPage} />

当访问/users,HomePage 和 UserPage 都会被渲染

const PrimaryLayout = () => (
  <div className="primary-layout">
    <PrimaryHeader />
    <main>
      <Switch>
        <Route path="/" exact component={HomePage} />                // 使用exact来精准匹配
        <Route path="/users/add" component={UserAddPage} />     // /users/add 放在 /users前面就可以避免对/users使用exact
        <Route path="/users" component={UsersPage} />                 // /users 放在 /users/add后面就可以避免对/users使用exact
        <Redirect to="/" />                                                                   // 都不匹配时,走 redirect
      </Switch>
    </main>
  </div>
)

3、一些技巧

<Switch>
        <Route path={props.match.path} exact component={BrowseUsersPage} />
        <Route path={`${props.match.path}/:userId`} component={UserProfilePage} />
</Switch>
<Route path={`/users/:userId(\\d+)`} component={UserProfilePage} />   // /users/edit 不会匹配,/users/123才会匹配
// 1、取查询字符串
const parsed = queryString.parse(location.search);  // location.search='?foo=bar'
console.log(parsed);    //  {foo: 'bar'}

// 2、取hash
const parsedHash = queryString.parse(location.hash);  // location.hash = '#token=bada55cafe'
console.log(parsedHash);  // {token: 'bada55cafe'}
// 3、制作location.search
parsed.foo = 'unicorn';
parsed.ilike = 'pizza';
const stringified = queryString.stringify(parsed);      //  'foo=unicorn&ilike=pizza'
location.search = stringified;
// note that `location.search` automatically prepends a question mark
console.log(location.search);       //  '?foo=unicorn&ilike=pizza'
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>
    )
  }
}

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)
// wrapping/composing
const FadingRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={props => (
    <FadeIn>
      <Component {...props}/>
    </FadeIn>
  )}/>
)
<FadingRoute path="/cool" component={Something}/>

children // 不管路径是否匹配,总是渲染。只是当路径不匹配时,match为null

<ul>
  <ListItemLink to="/somewhere"/>
  <ListItemLink to="/somewhere-else"/>
</ul>

const ListItemLink = ({ to, ...rest }) => (
  <Route path={to} children={({ match }) => (
    <li className={match ? 'active' : ''}>
      <Link to={to} {...rest}/>
    </li>
  )}/>
)

参考

上一篇 下一篇

猜你喜欢

热点阅读