React Router 路由【转】

@一棵菜菜  June 13, 2019

react使用react-router-dom

路由跳转是单页面应用的跳转。即整个网站在访问过程中只会加载一次HTML文件

好处:减少HTML加载次数,提高性能。

但如果使用<a />跳转,每点击一次或者一个a标签,都会重新加载整个网页(html)。

1. <Link>

为你的应用提供声明式的、可访问的导航链接。

import { Link, Redirect, withRouter } from "react-router-dom”;

... 
// 跳转链接
<Link className="login" to="/login">登录</Link>
// 直接跳转
<Redirect to="/" />
...

export default withRouter(Detail);

2. <Redirect>

使用 会导航到一个新的位置。新的位置将覆盖历史堆栈中的当前条目,例如服务器端重定向(HTTP 3xx)。
属性:to、push等。

push: boolean值,如果为 true,重定向会将新的位置推入历史记录,而不是替换当前条目。
import { Route, Redirect } from 'react-router-dom';

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

3. <Route>

在其 path 属性与某个 location 匹配时呈现一些 UI。
属性:
path: string,可以是 path-to-regexp 能够理解的任何有效的 URL 路径。
exact: bool,如果为 true,则只有在 path 完全匹配 location.pathname 时才匹配。

<Router>
  <div>
    <Route exact path="/" component={Home} />
    <Route path="/news" component={News} />
  </div>
</Router>

路由的渲染方式

使用 渲染一些内容有以下三种方式:

<Route component>  // 常用
<Route render>
<Route children>
在不同的情况下使用不同的方式。在指定的 <Route> 中,你应该只使用其中的一种。
优先级:<Route component> > <Route render> > <Route children>,因此不要在同一个 中同时使用多个。

component

指定只有当位置匹配时才会渲染的 React 组件,该组件会接收 route props 作为属性。

<Router>

所有 Router 组件的通用低阶接口。通常情况下,应用程序只会使用其中一个高阶 Router:

<BrowserRouter>
<HashRouter>
<MemoryRouter>
<NativeRouter>
<StaticRouter>

### <Switch>

用于渲染与路径匹配的第一个子 <Route><Redirect>

这与仅仅使用一系列 <Route> 有何不同?
<Switch> 只会渲染一个路由。相反,仅仅定义一系列 <Route> 时,每一个与路径匹配的 <Route> 都将包含在渲染范围内。考虑如下代码:

<Route path="/about" component={About} />
<Route path="/:user" component={User} />
<Route component={NoMatch} />

如果 URL 是 /about,那么 <About><User> <NoMatch> 将全部渲染,因为它们都与路径匹配。这是通过设计,允许我们以很多方式将 组合成我们的应用程序,例如侧边栏和面包屑、引导标签等。
但是,有时候我们只想选择一个 <Route> 来呈现。比如我们在 URL 为 /about 时不想匹配 /:user(或者显示我们的 404 页面),这该怎么实现呢?以下就是如何使用 <Switch> 做到这一点:

import { Switch, Route } from 'react-router';

<Switch>
  <Route exact path="/" component={Home} />
  <Route path="/about" component={About} />
  <Route path="/:user" component={User} />
  <Route component={NoMatch} />
</Switch>

现在,当我们在 /about 路径时,<Switch> 将开始寻找匹配的 <Route>。我们知道,<Route path="/about" /> 将会被正确匹配,这时 <Switch> 会停止查找匹配项并立即呈现 <About>。同样,如果我们在 /michael 路径时,那么 <User> 会呈现。


读取路由参数【待补充】

我的文章


路由在事件处理过程中跳转

可以用下面这个方法,也可以使用react-roter v4中提供的useHistory Hook

// history.js
const createHistory = require("history").createBrowserHistory;
export default createHistory();

// app.js
import history from "./history";
class App extends Component {
  render() {
    return (
      <Provider store={store}>
        <Router history={history}>
          <Switch>
            <AuthValidation routerConfig={routeConfig} />
          </Switch>
        </Router>
      </Provider>
    );
  }
}

export default App;

// 组件中使用
import history from '../../history';
history.push('/home');

第二company的路由例子

'../../routes':

const routes = [
  {
    path: '/',
    exact: true,
    component(props) {
      return <Bundle {...props} load={() => import('../pages/map')} />;
    }
  },
  {
    path: '/alipay',
    component(props) {
      return <Bundle {...props} load={() => import('../pages/land_page')} />;
    }
  },...
import { Switch, Route } from 'react-router';
import routes from '../../routes';

ReactDOM.render(
  <Provider store={store}>
    <Router history={history}>
     // 简写了,实际是在App组件中写的Switch
      {/* <Route component={App} /> */}
      <Switch>
          {routes.map((route, i) => (
            <Route
              key={i}
              exact={!!route.exact}
              path={route.path}
              component={route.component}
            />
          ))}
          <Route component={NotFound} />
        </Switch>
    </Router>
  </Provider>,
  document.getElementById('app'));
);

原文地址《React Router DOM 中文文档(一)》
推荐阮一峰的文章

添加新评论