2. React-Router的基本使用

14,696 阅读4分钟

《react-router-dom源码揭秘》系列

1. Context - React跨组件访问数据的利器
3. react-router-dom源码揭秘 - BrowserRouter

今天再给大家带来一篇翻译文章。原文来自react-router-dom官网

这篇文章,是我们react-router-dom源码揭秘系列的第二篇文章。同样是预备知识。

想看第一篇文章的客官请走这边。Context - React跨组件访问数据的利器

基本组件

React Router中有三类组件:

  • router 组件(BrowserRouter,HashRouter)
  • route matching 组件(Route,Switch)
  • navigation 组件(Link)

使用react-router-dom之前,我们需要在工程路径下安装这个包

npm install react-router-dom

安装完成后,上面所列出的这些组件,我们可以通过react-router-dom得到。

import { BrowserRouter, Route, Link } from "react-router-dom";

Routers

基于React Router的web应用,根组件应该是一个router组件(BrowserRouter,HashRouter)。 项目中,react-router-dom提供了和两种路由。两种路由都会创建一个history对象。如果我们的应用有服务器响应web的请求,我们通常使用<BrowserRouter>组件; 如果使用静态文件服务器,则我们应该使用<HashRouter>组件

import { BrowserRouter } from "react-router-dom";
ReactDOM.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>,
  holder
);

路由匹配

react-router-dom中有两个匹配路由的组件:<Route> 和 <Switch>.

import { Route, Switch } from "react-router-dom";

路由匹配是通过将<Route>组件的path属性与当前的location的pathname进行比较来完成的。当一个<Route>匹配了,它所对应的组件内容将被渲染出来。 不匹配,则渲染null。如果一个<Route>没有path属性,他的组件对应内容将一直被渲染出来。

// 当 location = { pathname: '/about' }
<Route path='/about' component={About}/> // 路径匹配成功,渲染 <About/>组件
<Route path='/contact' component={Contact}/> // 路径不匹配,渲染 null
<Route component={Always}/> // 该组件没有path属性,其对应的<Always/>组件会一直渲染

我们可以在组件树的任何位置放置<Route>组件。但是更常见的情况是将几个<Route>写在一起。<Switch>组件可以用来将多个<Route>“包裹”在一起。

多个组件在一起使用时,并不强制要求使用<Switch>组件,但是使用<Switch>组件却是非常便利的。<Switch>会迭代它下面的所有<Route>子组件,并只渲染第一个路径匹配的<Route>。

<Switch>
  <Route exact path="/" component={Home} />
  <Route path="/about" component={About} />
  <Route path="/contact" component={Contact} />
</Switch>

<Switch>
  <Route exact path="/" component={Home} />
  <Route path="/about" component={About} />
  <Route path="/contact" component={Contact} />
  {/* 如果上面的Route的路径都没有匹配上,则 <NoMatch>被渲染,我们可以在此组件中返回404 */}
  <Route component={NoMatch} />
</Switch>

Route Rendering Props

<Route>匹配时所显示的组件,有三种写法:

具体用法可以参照<Route>文档,这里我们先简单介绍一下component和render两种方法。

component

在使用<Route>时,如果我们想渲染的内容已经有对应的组件,则可以直接使用component的方法。例如:

<Route path="/user/:username" component={User} />;

function User({ match }) {
  return <h1>Hello {match.params.username}!</h1>;
}

render

render方法直接使用一个内联函数来渲染内容。

// convenient inline rendering
<Route path="/home" render={() => <div>Home</div>}/>

注意:

不要将component属性设置为一个函数,然后在其内部渲染组件。这样会导致已经存在的组件被卸载,然后重写创建一个新组件,而不是仅仅对组件进行更新。

const Home = () => <div>Home</div>;

const App = () => {
  const someVariable = true;

  return (
    <Switch>
      {/* these are good */}
      <Route exact path="/" component={Home} />
      <Route
        path="/about"
        render={props => <About {...props} extra={someVariable} />}
      />
      {/* do not do this */}
      <Route
        path="/contact"
        component={props => <Contact {...props} extra={someVariable} />}
      />
    </Switch>
  );
};

Navigation

React Router提供了一个组件用来在应用中添加link。当<Link>渲染时,一个<a>标签在html页面中被创建出来。

<Link to="/">Home</Link>
// <a href='/'>Home</a>

<NavLink>组件是一个特殊的<Link>组件。当它的path与当前location匹配时,可以自定义其样式来表示当前页面位置。

// location = { pathname: '/react' }
<NavLink to="/react" activeClassName="hurray">
  React
</NavLink>
// <a href='/react' className='hurray'>React</a>

当需要页面重定向时,我们可以使用<Redirect>组件。当一个<Redirect>组件被渲染时,页面将被渲染到<Redirect>组件的to属性指定的位置上。

<Route exact path="/" render={() => (
  loggedIn ? (
    <Redirect to="/dashboard"/>
  ) : (
    <PublicHomePage/>
  )
)}/>