React-Router-Dom 4 API


1. 路由器 Router

a)BrowserRouter

返回目錄

使用 HTML5 的 history API (pushState, replaceState 和 popstate 事件) 來保持 UI 與 URL 同步的<router>

import { BrowserRouter } from 'react-router-dom'

<BrowserRouter
  basename={optionalString}
  forceRefresh={optionalBool}
  getUserConfirmation={optionalFunc}
  keyLength={optionalNumber}
>
  <App />
</BrowserRouter>

basename

返回目錄

  • 類型:string
  • 說明:所有位置的基本URL。根據服務器目錄設置其目錄。以/開頭,無需/結尾
<BrowserRouter basename="/calendar" />
<Link to="/today"/> <!-- renders <a href="/calendar/today"> -->

getUserConfirmation

返回目錄

  • 類型:func
  • 說明:用於確認跳轉(confirm navigation)的函數。默認用 window.confirm.
<BrowserRouter
  getUserConfirmation={(message, callback) => {
    // this is the default behavior
    const allowTransition = window.confirm(message);
    callback(allowTransition);
  }}
/>

forceRefresh

點我返回目錄

  • 類型:bool
  • 說明:如果爲真,router 將在頁面導航中使用整頁刷新。可使用此功能模擬傳統服務器呈現的在頁面跳轉之間進行整頁刷新的方式。
<BrowserRouter forceRefresh={true} />

keyLength

返回目錄

  • 類型:number
  • 說明:location.key 的長度。默認爲 6 位
<BrowserRouter keyLength={12} />

children

返回目錄

  • 類型:node|
  • 說明:用於渲染的單個子元素

說明: 當 React 的版本 < 16 時, 必須使用單個子元素,因爲 render 方法不能返回多個元素. 如果需要多個元素,可以嘗試將它們包裝在一個額外的 <div> 中


b)HashRouter

返回目錄

使用 URL 的 hash 部分 (即 window.location.hash) 來保持 UI 與 URL 同步的<router>

import { HashRouter } from 'react-router-dom'

<HashRouter
  basename={optionalString}
  getUserConfirmation={optionalFunc}
  hashType={optionalString}
>
  <App />
</HashRouter>

重要說明:<HashHistory> 不支持 location.key 或 location.state。在以前的版本中,我們試圖填充行爲,但有些邊緣情況我們無法解決。任何需要此行爲的代碼或插件都無法工作。由於此技術僅用於支持傳統瀏覽器,因此建議將服務器配置爲使用 <BrowserHistory>。

basename

返回目錄

  • 類型:string
  • 說明:所有位置的基本URL。根據服務器目錄設置其目錄。以/開頭,無需/結尾
<HashRouter basename="/calendar"/>
<Link to="/today"/> <!-- renders <a href="#/calendar/today"> -->

getUserConfirmation

返回目錄

  • 類型:func
  • 說明:用於確認跳轉(confirm navigation)的函數。默認用 window.confirm.
<HashRouter
  getUserConfirmation={(message, callback) => {
    // this is the default behavior
    const allowTransition = window.confirm(message);
    callback(allowTransition);
  }}
/>

hashType

返回目錄

  • 類型:string
  • 說明:用於 window.location.hash 的編碼類型。可用值爲:
    • “slash”- 默認。創建像 #/#/sunshine/lollipops的 hash
    • “noslash” - 創建像 ##sunshine/lollipops的 hash
    • “hashbang” - 創建 “ajax crawlable” (被Google廢棄) 的 hash,像 #!/#!/sunshine/lollipops

children

返回目錄

  • 類型:node
  • 說明:用於渲染的單個子元素

c)MemoryRouter

返回目錄
將“url”的 history 保存在內存中的<router>(不讀或寫地址欄)。適用於測試和非瀏覽器環境,如 React Native。

import { MemoryRouter } from "react-router-dom";

<MemoryRouter
  initialEntries={optionalArray}
  initialIndex={optionalNumber}
  getUserConfirmation={optionalFunc}
  keyLength={optionalNumber}
>
  <App />
</MemoryRouter>

initialEntries

返回目錄

  • 類型:array
  • 說明:history 棧中的 locations 數組。這些可能是具有{ pathname, search, hash, state } 或簡單字符串URL的完整 location 對象。
<MemoryRouter
  initialEntries={["/one", "/two", { pathname: "/three" }]}
  initialIndex={1}
>
  <App />
</MemoryRouter>

initialIndex

返回目錄

  • 類型:number
  • 說明:指定 initialEntries 數組中的初始位置的索引。

getUserConfirmation

返回目錄

  • 類型:func
  • 說明:用於確認跳轉(confirm navigation)的函數。當 <Prompt> 直接用於 <MemoryRouter> 時,必須使用此選項。

keyLength

返回目錄

  • 類型:number
  • 說明:location.key 的長度。默認爲 6 位
<MemoryRouter keyLength={12} />

children

返回目錄

  • 類型:node
  • 說明:用於渲染的單個子元素

d)Router

返回目錄

The common low-level interface for all router components. Typically apps will use one of the high-level routers instead:
所有路由器組件的通用低級接口。通常,app將使用高級路由器之一:

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

The most common use-case for using the low-level is to synchronize a custom history with a state management lib like Redux or Mobx. Note that this is not required to use state management libs alongside React Router, it’s only for deep integration.
使用低級最常見的用例是將自定義歷史與狀態管理庫(如redux或mobx)同步。請注意,在React路由器旁邊使用狀態管理libs不需要這樣做,它只用於深度集成。

import React from "react";
import ReactDOM from "react-dom";
import { Router } from "react-router";
import { createBrowserHistory } from "history";

const history = createBrowserHistory();

ReactDOM.render(
  <Router history={history}>
    <App />
  </Router>,
  node
);

history

點我返回目錄

  • 類型:object
  • 說明:A history object to use for navigation.
    用於導航的歷史記錄對象。
import React from "react";
import ReactDOM from "react-dom";
import { createBrowserHistory } from "history";

const customHistory = createBrowserHistory();

ReactDOM.render(<Router history={customHistory} />, node);

children

返回目錄

  • 類型:node
  • 說明:A single child element to render.
<Router>
  <App />
</Router>

e)StaticRouter

返回目錄

A <Router> that never changes location.

This can be useful in server-side rendering scenarios when the user isn’t actually clicking around, so the location never actually changes. Hence, the name: static. It’s also useful in simple tests when you just need to plug in a location and make assertions on the render output.
這在服務器端渲染場景中非常有用,當用戶沒有實際單擊時,這樣位置就不會實際更改。因此,名稱爲:static。當您只需要插入一個位置並對渲染輸出進行斷言時,它在簡單測試中也很有用

Here’s an example node server that sends a 302 status code for s and regular HTML for other requests:
下面是一個示例節點服務器,它爲s發送302狀態代碼,爲其他請求發送常規HTML:

import http from "http";
import React from "react";
import ReactDOMServer from "react-dom/server";
import { StaticRouter } from "react-router";

http
  .createServer((req, res) => {
    // This context object contains the results of the render
    const context = {};

    const html = ReactDOMServer.renderToString(
      <StaticRouter location={req.url} context={context}>
        <App />
      </StaticRouter>
    );

    // context.url will contain the URL to redirect to if a <Redirect> was used
    if (context.url) {
      res.writeHead(302, {
        Location: context.url
      });
      res.end();
    } else {
      res.write(html);
      res.end();
    }
  })
  .listen(3000);

basename

返回目錄

  • 類型:string
  • 說明:The base URL for all locations. A properly formatted basename should have a leading slash, but no trailing slash.
    所有位置的基本URL。
    格式正確的basename應該有一個前導斜槓,但不能有尾隨斜槓。
<StaticRouter basename="/calendar">
  <Link to="/today"/> // renders <a href="/calendar/today">
</StaticRouter>

location

返回目錄

  • 類型:string
  • 說明:The URL the server received, probably req.url on a node server.
    服務器接收到的URL,可能是節點服務器上的req.url。
<StaticRouter location={req.url}>
  <App />
</StaticRouter>
  • 類型:object
  • 說明:A location object shaped like { pathname, search, hash, state }
    形狀像{ pathname, search, hash, state } 的 location 對象
<StaticRouter location={{ pathname: "/bubblegum" }}>
  <App />
</StaticRouter>

context

點我返回目錄

  • 類型:object
  • 說明:A plain JavaScript object. During the render, components can add properties to the object to store information about the render.
    一個普通的javascript對象。在渲染過程中,組件可以向對象添加屬性以存儲有關渲染的信息。
const context = {}
<StaticRouter context={context}>
  <App />
</StaticRouter>

When a matches, it will pass the context object to the component it renders as the staticContext prop. Check out the Server Rendering guide for more information on how to do this yourself.
當一個匹配時,它將把上下文對象傳遞給它呈現爲staticContext屬性的組件。有關如何自己執行此操作的詳細信息,請參閱《服務器呈現指南》。

After the render, these properties can be used to to configure the server’s response.
渲染之後,這些屬性可用於配置服務器的響應。

if (context.status === "404") {
  // ...
}

children

返回目錄

  • 類型:node
  • 說明:A single child element to render.

Note: On React < 16 you must use a single child element since a render method cannot return more than one element. If you need more than one element, you might try wrapping them in an extra <div>.


2. 路由

返回目錄

a)Route

The Route component is perhaps the most important component in React Router to understand and learn to use well. Its most basic responsibility is to render some UI when its path matches the current URL.
路由組件可能是反應路由器中理解和學習良好使用的最重要組件。它最基本的職責是在位置與路由路徑匹配時呈現一些UI。

Consider the following code:
考慮以下代碼:

import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router, Route } from 'react-router-dom'

ReactDOM.render(
  <Router>
    <div>
      <Route exact path="/">
        <Home />
      </Route>
      <Route path="/news">
        <NewsFeed />
      </Route>
    </div>
  </Router>,
  node
);

If the location of the app is / then the UI hierarchy will be something like:
如果 app 的位置是 / 的話,那麼UI層會有點像:

<div>
  <Home/>
  <!-- react-empty: 2 -->
</div>

And if the location of the app is /news then the UI hierarchy will be:
如果 app 的位置是 /news,那麼UI層將會是:

<div>
  <!-- react-empty: 1 -->
  <NewsFeed/>
</div>

The “react-empty” comments are just implementation details of React’s null rendering. But for our purposes, it is instructive. A Route is always technically “rendered” even though its rendering null. When the 's path matches the current URL, it renders its children (your component).
“react empty” 註釋只是 React 的空呈現的實現細節。但就我們的目的而言,這是有指導意義的。一個路由在技術上總是“渲染”,即使其渲染爲空。一旦應用程序位置與路由路徑匹配,就會呈現組件。

Route render methods 路由渲染的方式

返回目錄

The recommended method of rendering something with a is to use children elements, as shown above. There are, however, a few other methods you can use to render something with a . These are provided mostly for supporting apps that were built with earlier versions of the router before hooks were introduced.

一個有三種方式來渲染:

  • <Route component>
  • <Route render>
  • <Route children>

You should use only one of these props on a given . See their explanations below to understand the differences between them.

舊–
Each is useful in different circumstances. You should use only one of these props on a given . See their explanations below to understand why you have 3 options. Most of the time you’ll use component.

每一種都在不同的情況下有用。在給定的<Route>上應該只使用其中一種屬性。請參閱下面他們的解釋,瞭解您爲什麼有3個選項。大多數情況下,您將使用component。

Route props 路由的參數

返回目錄

All three render methods will be passed the same three route props
所有的三種渲染方式將會接收到同樣的三個路由參數

  • match
  • location
  • history

component

返回目錄

A React component to render only when the location matches. It will be rendered with route props.
僅當位置匹配時才渲染的 React 組件。它將使用路由參數渲染。

import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router, Route } from "react-router-dom";

// All route props (match, location and history) are available to User
function User(props) {
  return <h1>Hello {props.match.params.username}!</h1>;
}

ReactDOM.render(
  <Router>
    <Route path="/user/:username" component={User} />
  </Router>,
  node
);

When you use component (instead of render or children, below) the router uses React.createElement to create a new React element from the given component. That means if you provide an inline function to the component prop, you would create a new component every render. This results in the existing component unmounting and the new component mounting instead of just updating the existing component. When using an inline function for inline rendering, use the render or the children prop (below).

當使用component(而不是下面的render或children)時,路由器使用react.createElement從給定組件創建新的react元素。這意味着,如果爲組件屬性提供內聯函數,則每次渲染都將創建一個新組件。這將導致現有組件卸載和新組件安裝,而不僅僅是更新現有組件。當使用內聯函數進行內聯渲染時,請使用render或children屬性(如下)。

render

返回目錄

  • 類型:func

This allows for convenient inline rendering and wrapping without the undesired remounting explained above.
這樣可以方便地進行內聯渲染和包裝,而無需上述不需要的重新安裝。

Instead of having a new React element created for you using the component prop, you can pass in a function to be called when the location matches. The render prop function has access to all the same route props (match, location and history) as the component render prop.
不必使用component爲您創建新的react元素,您可以傳入一個函數,當位置匹配時調用該函數。render參數函數可以訪問與component的渲染參數相同的所有路由參數(match, location 和 history)。

import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router, Route } from "react-router-dom";

// convenient inline rendering
ReactDOM.render(
  <Router>
    <Route path="/home" render={() => <div>Home</div>} />
  </Router>,
  node
);

// wrapping/composing
// You can spread routeProps to make them available to your rendered Component
function FadingRoute({ component: Component, ...rest }) {
  return (
    <Route
      {...rest}
      render={routeProps => (
        <FadeIn>
          <Component {...routeProps} />
        </FadeIn>
      )}
    />
  );
}

ReactDOM.render(
  <Router>
    <FadingRoute path="/cool" component={Something} />
  </Router>,
  node
);

Warning: <Route component> takes precedence over <Route render> so don’t use both in the same <Route>.
警告:<Route component>優先於<Route render>,因此不要在同一<Route>中同時使用這兩者。

children

返回目錄

  • 類型:func

Sometimes you need to render whether the path matches the location or not. In these cases, you can use the function children prop. It works exactly like render except that it gets called whether there is a match or not.
有時需要渲染路徑是否與位置匹配。在這些情況下,您可以使用函數children 屬性。它的工作原理與render完全相同,只是不管是否匹配都會調用它。

The children render prop receives all the same route props as the component and render methods, except when a route fails to match the URL, then match is null. This allows you to dynamically adjust your UI based on whether or not the route matches. Here we’re adding an active class if the route matches
子級渲染屬性接收與組件和渲染方法相同的所有路由屬性,除非路由與URL不匹配,否則匹配爲空。這允許您根據路由是否匹配來動態調整UI。這裏,如果路由匹配,我們將添加一個活動類

import React from "react";
import ReactDOM from "react-dom";
import {
  BrowserRouter as Router,
  Link,
  Route
} from "react-router-dom";

function ListItemLink({ to, ...rest }) {
  return (
    <Route
      path={to}
      children={({ match }) => (
        <li className={match ? "active" : ""}>
          <Link to={to} {...rest} />
        </li>
      )}
    />
  );
}

ReactDOM.render(
  <Router>
    <ul>
      <ListItemLink to="/somewhere" />
      <ListItemLink to="/somewhere-else" />
    </ul>
  </Router>,
  node
);

This could also be useful for animations:

這也適用於animations

<Route
  children={({ match, ...rest }) => (
    {/* Animate will always render, so you can use lifecycles
        to animate its child in and out */}
    <Animate>
      {match && <Something {...rest}/>}
    </Animate>
  )}
/>


Warning: <Route children> takes precedence over both <Route component> and <Route render> so don’t use more than one in the same .

Warning: Both <Route component> and <Route render> take precedence over <Route children> so don’t use more than one in the same .


警告:<Route component>和<Route render>都優先於<Route children>,因此不要在同一中使用多個。

path

返回目錄

  • 類型:string | string[]
  • 說明:被path-to-regexp@^1.7.0 理解的任何有效的URL路徑或路徑數組
<Route path="/users/:id">
  <User />
</Route>
<Route path={["/users/:id", "/profile/:id"]}>
  <User />
</Route>

Routes without a path always match.
沒有路徑的路由總是匹配的。

exact

返回目錄

  • 類型:bool
  • 說明:When true, will only match if the path matches the location.pathname exactly.
    如果爲true,則僅當路徑與location.pathname完全匹配時才匹配。
<Route exact path="/one">
  <About />
</Route>
path location.pathname exact matches?
/one /one/two true no
/one /one/two false yes

strict

返回目錄

  • 類型:bool
  • 說明:When true, a path that has a trailing slash will only match a location.pathname with a trailing slash. This has no effect when there are additional URL segments in the location.pathname.
    如果爲true,則帶有尾隨斜槓的路徑將只與帶有尾隨斜槓的location.pathname匹配。當location.pathname中有其他的url段時,這不起作用。
<Route strict path="/one/">
  <About />
</Route>
path location.pathname matches?
/one/ /one no
/one/ /one/ yes
/one/ /one/two yes

Warning: strict can be used to enforce that a location.pathname has no trailing slash, but in order to do this both strict and exact must be true.


警告:Strict可用於強制location.pathname沒有尾隨斜槓,但要執行此操作,Strict和Exact都必須爲true。

<Route exact strict path="/one">
  <About />
</Route>
path location.pathname matches?
/one /one yes
/one /one/ no
/one /one/two no

location

返回目錄

  • 類型:object

A <Route> element tries to match its path to the current history location (usually the current browser URL). However, a location with a different pathname can also be passed for matching.
元素嘗試將其路徑與當前歷史記錄位置(通常是當前瀏覽器URL)匹配。但是,也可以傳遞具有不同路徑名的位置進行匹配。

This is useful in cases when you need to match a <Route> to a location other than the current history location, as shown in the Animated Transitions example.
這在需要將<Route>匹配到當前歷史位置以外的位置時非常有用,如動畫轉換示例中所示。

If a <Route> element is wrapped in a <Switch> and matches the location passed to the <Switch> (or the current history location), then the location prop passed to <Route> will be overridden by the one used by the <Switch> (given here).


如果一個<Route>元素包裝在一個<Switch>中,並且與傳遞給<Switch>的位置(或當前歷史位置)匹配,那麼傳遞給<Route>的位置屬性將被<Switch>使用的屬性覆蓋(此處給出)。

sensitive

返回目錄

  • 類型:bool
  • 說明:When true, will match if the path is case sensitive.
    如果爲true,則在路徑區分大小寫時匹配。
<Route sensitive path="/one">
  <About />
</Route>
path location.pathname sensitive matches?
/one /one true yes
/One /one true no
/One /one false yes

b)Switch

返回目錄

Renders the first child <Route> or <Redirect> that matches the location.
渲染 第一個與位置匹配的子級<Route>或<Redirect>。

How is this different than just using a bunch of <Route>s?
這與使用一組有什麼不同?

<Switch> is unique in that it renders a route exclusively. In contrast, every <Route> that matches the location renders inclusively. Consider this code:
<Switch>是唯一的,因爲它只渲染路由。與此相反,與位置匹配的每個<Route>都包含在內。考慮此代碼:

import { Route } from "react-router";

let routes = (
  <div>
    <Route path="/about">
      <About />
    </Route>
    <Route path="/:user">
      <User />
    </Route>
    <Route>
      <NoMatch />
    </Route>
  </div>
);

If the URL is /about, then , , and will all render because they all match the path. This is by design, allowing us to compose s into our apps in many ways, like sidebars and breadcrumbs, bootstrap tabs, etc.
如果URL是/about,則、和將全部渲染,因爲它們都與路徑匹配。這是通過設計實現的,允許我們以多種方式將組合到應用程序中,比如側邊欄和麪包屑導航、引導選項卡等。

Occasionally, however, we want to pick only one to render. If we’re at /about we don’t want to also match /:user (or show our “404” page). Here’s how to do it with Switch:
但是,有時我們只想選擇一個進行渲染。如果我們在/about 我們不想也匹配/:user(或顯示我們的“404”頁)。下面介紹如何使用Switch:

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

let routes = (
  <Switch>
    <Route exact path="/">
      <Home />
    </Route>
    <Route path="/about">
      <About />
    </Route>
    <Route path="/:user">
      <User />
    </Route>
    <Route>
      <NoMatch />
    </Route>
  </Switch>
);

Now, if we’re at /about, <Switch> will start looking for a matching <Route>. <Route path="/about"/> will match and <Switch> will stop looking for matches and render <About>. Similarly, if we’re at /michael then <User> will render.
現在,如果我們是/about,將開始尋找匹配的。將匹配,將停止查找匹配項並渲染。同樣,如果我們是/michael,那麼將被渲染。

This is also useful for animated transitions since the matched <Route> is rendered in the same position as the previous one.
這對於動畫轉換也很有用,因爲匹配的<Route>與前一個位置渲染在同一位置。

let routes = (
  <Fade>
    <Switch>
      {/* there will only ever be one child here */}
      <Route />
      <Route />
    </Switch>
  </Fade>
);

let routes = (
  <Fade>
    {/* there will always be two children here,
        one might render null though, making transitions
        a bit more cumbersome to work out */}
    <Route />
    <Route />
  </Fade>
);

location

返回目錄

  • 類型:object
  • 說明:A location object to be used for matching children elements instead of the current history location (usually the current browser URL).
    用於匹配子元素而不是當前歷史記錄位置(通常是當前瀏覽器URL)的location對象。

children

返回目錄

  • 類型:node

All children of a <Switch> should be <Route> or <Redirect> elements. Only the first child to match the current location will be rendered.
<Switch>的所有子元素都應該是<Route>或<Redirect>元素。將只呈現與當前位置匹配的第一個子級。

<Route> elements are matched using their path prop and <Redirect> elements are matched using their from prop. A <Route> with no path prop or a <Redirect> with no from prop will always match the current location.
<Route>元素使用其路徑屬性匹配,而<Redirect>元素使用其from屬性匹配。沒有路徑道具的\或沒有from道具的<Redirect>將始終匹配當前位置。

When you include a <Redirect> in a <Switch>, it can use any of the <Route>'s location matching props: path, exact, and strict. from is just an alias for the path prop.
當您在<Switch>中包含<Redirect>時,它可以使用任何<Route>的位置匹配屬性:path、exact和strict。from只是路徑屬性的別名。

If a location prop is given to the <Switch>, it will override the location prop on the matching child element.
如果爲<Switch>提供了location屬性,它將覆蓋匹配子元素上的location屬性。

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

let routes = (
  <Switch>
    <Route exact path="/">
      <Home />
    </Route>

    <Route path="/users">
      <Users />
    </Route>
    <Redirect from="/accounts" to="/users" />

    <Route>
      <NoMatch />
    </Route>
  </Switch>
);

c)Redirect

返回目錄

Rendering a <Redirect> will navigate to a new location. The new location will override the current location in the history stack, like server-side redirects (HTTP 3xx) do.
渲染 <Redirect> 將 navigate 到新 location。新位置將覆蓋歷史堆棧中的當前位置,如服務器端重定向(HTTP 3xx)所做的操作。

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

to

返回目錄

  • 類型:string
  • 說明:要重定向到的URL。path-to-regexp@^1.7.0可以理解的任何有效URL路徑。使用的所有url參數必須由from覆蓋。
<Redirect to="/somewhere/else" />
  • 類型:object
  • 說明:redirect 到的 location 。pathname 是 path-to-regexp@^1.7.0可以理解的任何有效URL路徑。
<Redirect
  to={{
    pathname: "/login",
    search: "?utm=your+face",
    state: { referrer: currentLocation }
  }}
/>

The state object can be accessed via this.props.location.state in the redirected-to component. This new referrer key (which is not a special name) would then be accessed via this.props.location.state.referrer in the Login component pointed to by the pathname ‘/login’
可以通過重定向到組件中的this.props.location.state訪問state對象。然後,可以通過路徑名“/login”指向的登錄組件中的this.props.location.state.referer訪問此新的referer密鑰(不是特殊名稱)。

push

返回目錄

  • 類型:bool
  • 說明:如果爲“真”,則重定向會將新條目推送到歷史記錄中,而不是替換當前條目。
<Redirect push to="/somewhere/else" />

from

返回目錄

  • 類型:string
  • 說明:重定向的 pathname 。path-to-regexp@^1.7.0可以理解的任何有效URL路徑。所有匹配的URL參數都提供給匹配中的。必須包含中使用的所有參數。忽略了收件人未使用的其他參數.
    這隻能用於在<switch>內部呈現<redirect>時匹配位置。有關詳細信息,請參閱<switch children>。
<Switch>
  <Redirect from='/old-path' to='/new-path' />
  <Route path='/new-path'>
    <Place />
  </Route>
</Switch>

// Redirect with matched parameters
<Switch>
  <Redirect from='/users/:id' to='/users/profile/:id'/>
  <Route path='/users/profile/:id'>
    <Profile />
  </Route>
</Switch>

exact

返回目錄

  • 類型:bool
  • 說明:參考中的相關屬性
    Note: This can only be used in conjunction with from to exactly match a location when rendering a inside of a . See for more details.
<Switch>
  <Redirect exact from="/" to="/home" />
  <Route path="/home">
    <Home />
  </Route>
  <Route path="/about">
    <About />
  </Route>
</Switch>

strict

返回目錄

  • 類型:bool
  • 說明:參考中的相關屬性
    Note: This can only be used in conjunction with from to strictly match a location when rendering a inside of a . See for more details.
<Switch>
  <Redirect strict from="/one/" to="/home" />
  <Route path="/home">
    <Home />
  </Route>
  <Route path="/about">
    <About />
  </Route>
</Switch>

sensitive

返回目錄

  • 類型:bool
  • 說明:參考中的相關屬性

3. 跳轉

a)Link

返回目錄
爲應用提供聲明、可訪問的跳轉鏈接(navigate)。

import { Link } from 'react-router-dom'
<Link to="/about">About</Link>

to

返回目錄

  • 類型:string
  • 說明:鏈接的字符串形式,創建連接該位置的 pathname、search 和 hash 屬性。
    <Link to="/courses?sort=name" />
    
  • 類型:object
  • 說明:鏈接的對象形式,可以具有以下任何屬性的對象:
    • pathname:表示要 link 到的路徑的字符串
    • search: 表示要查詢參數的字符串
    • hash: 表示要放入 URL 中的 hash,如:#a-hash.
    • state: 要傳到該 location 的 State
    <Link
      to={{
        pathname: "/courses",
        search: "?sort=name",
        hash: "#the-hash",
        state: { fromDashboard: true }
      }}
    />
    
  • 類型:function
  • 說明:鏈接的函數形式,當前 location 作爲參數傳遞給該函數,並 return 一個 新的 location。類型爲 string 或 object
    <Link to={location => ({ ...location, pathname: "/courses" })} />
    <Link to={location => `${location.pathname}?sort=name`} />
    

replace

返回目錄

  • 類型:bool
  • 說明:如果爲真,點擊該 link 將替換 history 堆棧中的當前條目,而不是新添加一條。
 <Link to="/courses" replace />

b)NavLink

返回目錄
一個特殊版本的 Link,當它匹配當前URL時,會在元素上增加樣式相關的屬性(從而達到高亮標記的效果)

import { NavLink } from 'react-router-dom'
<NavLink to="/about">About</NavLink>

activeClassName

返回目錄

  • 類型:string

  • 說明:當元素處於活動狀態時提供該元素的類。默認的給定類是活動的。這將與classname屬性結合在一起。

    The class to give the element when it is active. The default given class is active. This will be joined with the className prop.

<NavLink to="/faq" activeClassName="selected">
  FAQs
</NavLink>

activeStyle

返回目錄

  • 類型:object
  • 說明:活動時應用於元素的樣式。
    The styles to apply to the element when it is active.
<NavLink
  to="/faq"
  activeStyle={{
    fontWeight: "bold",
    color: "red"
  }}
>
  FAQs
</NavLink>

exact

返回目錄

  • 類型:bool
  • 說明:如果爲true,則僅當位置完全匹配時才應用活動類/樣式
    When true, the active class/style will only be applied if the location is matched exactly.
<NavLink exact to="/profile">
  Profile
</NavLink>

strict

返回目錄

  • 類型:bool
  • 說明:如果爲true,則在確定位置是否與當前URL匹配時,將考慮位置路徑名的尾隨斜槓。請參閱文檔。
    When true, the trailing slash on a location’s pathname will be taken into consideration when determining if the location matches the current URL. See the documentation for more information.
<NavLink strict to="/events/">
  Events
</NavLink>

isActive

返回目錄

  • 類型:func
  • 說明:用於添加額外邏輯以確定鏈接是否處於活動狀態的函數。如果您想做的不僅僅是驗證 Link 的 pathname 是否與當前 URL 的 pathname 匹配,那麼應該使用此選項。
    A function to add extra logic for determining whether the link is active. This should be used if you want to do more than verify that the link’s pathname matches the current URL’s pathname.
<NavLink
  to="/events/123"
  isActive={(match, location) => {
    if (!match) {
      return false;
    }

    // only consider an event active if its event id is an odd number
    const eventID = parseInt(match.params.eventID);
    return !isNaN(eventID) && eventID % 2 === 1;
  }}
>
  Event 123
</NavLink>

location

返回目錄

  • 類型:object
  • 說明:isActive 比較當前歷史 location (通常是當前的 browser URL)。要與其他 location 進行比較,可以傳遞一個 location
    The isActive compares the current history location (usually the current browser URL). To compare to a different location, a location can be passed.

aria-current

返回目錄

  • 類型:string
  • 說明:活動鏈接上使用的 aria-current 屬性的值。可用值爲:
    • “page” - 默認。用於指示一組分頁鏈接中的link
    • “step” - 用於指示基於步驟的流程的步驟指示器中的link
    • “location” - 用於指示視覺上突出顯示爲流程圖當前 component 的 image
    • “date” - 用於指示日曆中的當前日期
    • “time” - 用於指示時間表中的當前時間
    • “true” - 用於指示導航鏈接是否處於活動狀態

The value of the aria-current attribute used on an active link. Available values are:

  • “page” - used to indicate a link within a set of pagination links
  • “step” - used to indicate a link within a step indicator for a step-based process
  • “location” - used to indicate the image that is visually highlighted as the current component of a flow chart
  • “date” - used to indicate the current date within a calendar
  • “time” - used to indicate the current time within a timetable
  • “true” - used to indicate if the NavLink is active
    Defaults to “page”.Based on WAI-ARIA 1.1 specifications

c)Prompt

返回目錄

用於在離開頁面前提示用戶。當應用程序進入一個應該阻止用戶跳轉的狀態時(就像一個表單被填了一半),請呈現一個。

import { Prompt } from 'react-router'

<Prompt
  when={formIsHalfFilledOut}
  message="Are you sure you want to leave?"
/>

message

返回目錄

  • 類型:string
  • 說明:當用戶試圖離開時提示用戶的消息。
<Prompt when={formIsHalfFilledOut} message="Are you sure?" />
  • 類型:func
  • 說明:將使用用戶試圖導航到的下一個位置和操作調用。返回一個字符串以向用戶顯示提示,或返回true以允許轉換。
<Prompt
  message={location =>
    location.pathname.startsWith("/app")
      ? true
      : `Are you sure you want to go to ${location.pathname}?`
  }
/>

when

返回目錄

  • 類型:bool
  • 說明:與有條件地渲染後面的不同,您可以始終渲染它,但在 when={true} or when={false} 時傳遞,以阻止或允許相應的導航。
<Prompt when={formIsHalfFilledOut} message="Are you sure?" />

4. 對象屬性

返回目錄

a)context.router

返回目錄

b)history

返回目錄

The term “history” and “history object” in this documentation refers to the history package, which is one of only 2 major dependencies of React Router (besides React itself), and which provides several different implementations for managing session history in JavaScript in various environments.
本文檔中的術語“history”和“history object”是指history包,它是React Router (除了React本身)僅有的兩個主要依賴項之一,它提供了幾種不同的實現,用於在不同環境中管理javascript中的會話歷史。

The following terms are also used:
還使用以下術語:

  • “browser history” - A DOM-specific implementation, useful in web browsers that support the HTML5 history API
    一種特定於DOM的實現,在支持HTML5 history API的Web瀏覽器中非常有用。
  • “hash history” - A DOM-specific implementation for legacy web browsers
    針對傳統Web瀏覽器的特定於DOM的實現
  • “memory history” - An in-memory history implementation, useful in testing and non-DOM environments like React Native
    內存中的history實現,在測試和非DOM環境(如React Native)中很有用

history objects typically have the following properties and methods:
history對象通常具有以下屬性和方法:

  • length - (number) The number of entries in the history stack
    history 棧中的條目數
  • action - (string) The current action (PUSH, REPLACE, or POP)
    當前的動作(PUSH, REPLACE, or POP)
  • location - (object) The current location. May have the following properties:
    當前的location。可能具有以下屬性:
    • pathname - (string) The path of the URL
      URL的路徑
    • search - (string) The URL query string
      URL查詢字符串
    • hash - (string) The URL hash fragment
    • state - (object) location-specific state that was provided to e.g. push(path, state) when this location was pushed onto the stack. Only available in browser and memory history.
      提供給特定location的state,例如,將此location推送到堆棧時的push(path,state)。僅在瀏覽器和內存歷史記錄中可用。
  • push(path, [state]) - (function) Pushes a new entry onto the history stack
    推送一個新條目進history堆棧
  • replace(path, [state]) - (function) Replaces the current entry on the history stack
    替換history 堆棧上的當前條目
  • go(n) - (function) Moves the pointer in the history stack by n entries
    將history堆棧中的指針移動n個條目
  • goBack() - (function) Equivalent to go(-1)
  • goForward() - (function) Equivalent to go(1)
  • block(prompt) - (function) Prevents navigation (see the history docs)
    阻止導航

history is mutable

返回目錄

The history object is mutable. Therefore it is recommended to access the location from the render props of <Route>, not from history.location. This ensures your assumptions about React are correct in lifecycle hooks. For example:
history對象是可變的。因此,建議從<Route>的渲染屬性訪問位置,而不是從history.location。這可以確保您對React的假設在生命週期鉤子中是正確的。例如:

class Comp extends React.Component {
  componentDidUpdate(prevProps) {
    // will be true
    const locationChanged =
      this.props.location !== prevProps.location;

    // INCORRECT, will *always* be false because history is mutable.
    const locationChanged =
      this.props.history.location !== prevProps.history.location;
  }
}

<Route component={Comp} />;

Additional properties may also be present depending on the implementation you’re using. Please refer to the history documentation for more details.
根據您使用的實現,還可能存在其他屬性。有關詳細信息,請參閱history文檔。

c)location

返回目錄

Locations represent where the app is now, where you want it to go, or even where it was. It looks like this:
location代表app的現在位置,你想要它去的地方,甚至是它原來的位置。看起來是這樣的:

{
  key: 'ac3df4', // not with HashHistory!
  pathname: '/somewhere'
  search: '?some=search-string',
  hash: '#howdy',
  state: {
    [userDefined]: true
  }
}

The router will provide you with a location object in a few places:
路由器將在幾個地方爲您提供一個位置對象:

  • <Route component> as this.props.location
  • <Route render> as ({ location }) => ()
  • <Route children> as ({ location }) => ()
  • withRouter as this.props.location

It is also found on history.location but you shouldn’t use that because its mutable. You can read more about that in the history doc.
它也可以在history.location上找到,但您不應該使用它,因爲它是可變的。你可以在歷史文件中瞭解更多。

A location object is never mutated so you can use it in the lifecycle hooks to determine when navigation happens, this is really useful for data fetching and animation.
location對象永遠不會發生變化,因此您可以在生命週期鉤子中使用它來確定何時進行導航,這對於數據獲取和動畫非常有用。

componentWillReceiveProps(nextProps) {
  if (nextProps.location !== this.props.location) {
    // navigated!
  }
}

You can provide locations instead of strings to the various places that navigate:
您可以爲導航的各個位置提供位置而不是字符串:

  • Web <Link to>
  • Native <Link to>
  • <Redirect to>
  • \history.push
  • \history.replace

Normally you just use a string, but if you need to add some “location state” that will be available whenever the app returns to that specific location, you can use a location object instead. This is useful if you want to branch UI based on navigation history instead of just paths (like modals).
通常,您只需要使用一個字符串,但是如果您需要添加一些“位置狀態”,當應用程序返回到特定位置時,它將可用,您可以使用一個位置對象。如果您希望基於導航歷史而不僅僅是路徑(如模態)來分支UI,那麼這非常有用。

// usually all you need
<Link to="/somewhere"/>

// but you can use a location instead
const location = {
  pathname: '/somewhere',
  state: { fromDashboard: true }
}

<Link to={location}/>
<Redirect to={location}/>
history.push(location)
history.replace(location)

Finally, you can pass a location to the following components:
最後,可以將位置傳遞給以下組件:

  • Route
  • Switch

This will prevent them from using the actual location in the router’s state. This is useful for animation and pending navigation, or any time you want to trick a component into rendering at a different location than the real one.
這將阻止他們使用路由器狀態下的實際位置。這對於動畫和掛起的導航很有用,或者在任何時候您想要欺騙一個組件,使其在與真實組件不同的位置進行渲染。

d)match

A match object contains information about how a <Route path> matched the URL. match objects contain the following properties:
match對象包含有關如何匹配URL的信息。match對象包含以下屬性:

  • params - (object) Key/value pairs parsed from the URL corresponding to the dynamic segments of the path
    從與路徑的動態段相對應的URL解析的鍵/值對
  • isExact - (boolean) true if the entire URL was matched (no trailing characters)
    如果整個URL匹配,則爲true(沒有尾隨字符)
  • path - (string) The path pattern used to match. Useful for building nested <Route>s
    用於匹配的路徑模式。用於構建嵌套的<Route>s
  • url - (string) The matched portion of the URL. Useful for building nested <Link>s
    URL的匹配部分。用於構建嵌套的<Link>s

You’ll have access to match objects in various places:
您可以在不同位置訪問match對象

  • <Route component> as this.props.match
  • <Route render> as ({ match }) => ()
  • <Route children> as ({ match }) => ()
  • withRouter as this.props.match
  • matchPath as the return value

If a Route does not have a path, and therefore always matches, you’ll get the closest parent match. Same goes for withRouter.
如果路由沒有路徑,因此始終匹配,則會得到最近的父匹配。withRouter也是如此。

null matches

返回目錄

A <Route> that uses the children prop will call its children function even when the route’s path does not match the current location. When this is the case, the match will be null. Being able to render a <Route>'s contents when it does match can be useful, but certain challenges arise from this situation.
即使路由的路徑與當前位置不匹配,使用子屬性的<Route>也將調用其children函數。在這種情況下,match將爲空。當匹配時能夠渲染<Route>的內容是有用的,但是這種情況會帶來一些挑戰。

The default way to “resolve” URLs is to join the match.url string to the “relative” path.
“解析”URL的默認方法是將match.url字符串連接到“relative”路徑

let path = `${match.url}/relative-path`;

If you attempt to do this when the match is null, you will end up with a TypeError. This means that it is considered unsafe to attempt to join “relative” paths inside of a <Route> when using the children prop.
如果在match爲空時嘗試執行此操作,則將以類型錯誤結束。這意味着當使用children prop時,嘗試連接<Route>內的“相對”路徑是不安全的。

A similar, but more subtle situation occurs when you use a pathless <Route> inside of a <Route> that generates a null match object.
當在生成空match對象的<Route>內部使用無路徑的<Route>時,會出現類似但更微妙的情況。

// location.pathname = '/matches'
<Route path='/does-not-match' children={({ match }) => (
  // match === null
  <Route render={({ match:pathlessMatch }) => (
    // pathlessMatch === ???
  )}/>
)}/>

Pathless <Route>s inherit their match object from their parent. If their parent match is null, then their match will also be null. This means that a) any child routes/links will have to be absolute because there is no parent to resolve with and b) a pathless route whose parent match can be null will need to use the children prop to render.


無路徑的<Route>s從其父對象繼承其match對象。如果他們的父match爲空,那麼他們的match也將爲空。這意味着a)任何routes/links都必須是絕對的,因爲沒有要解析的父路由;b)父match可以爲空的無路徑路由需要使用children屬性進行渲染。

e)matchPath

返回目錄

This lets you use the same matching code that <Route> uses except outside of the normal render cycle, like gathering up data dependencies before rendering on the server.
這允許您使用與<Route>使用的相同的匹配代碼,除了正常渲染週期之外,例如在服務器上渲染之前收集數據依賴項。

import { matchPath } from "react-router";

const match = matchPath("/users/123", {
  path: "/users/:id",
  exact: true,
  strict: false
});

pathname

返回目錄

The first argument is the pathname you want to match. If you’re using this on the server with Node.js, it would be req.path.
第一個參數是要匹配的路徑名。如果您在node.js服務器上使用它,它將是req.path

props

返回目錄

The second argument are the props to match against, they are identical to the matching props Route accepts:
第二個參數是要匹配的屬性,它們與匹配的屬性路由接受的屬性相同:

{
  path, // like /users/:id; either a single string or an array of strings
  strict, // optional, defaults to false
  exact, // optional, defaults to false
}

returns

返回目錄

It returns an object when provided pathname does match path prop.
如果提供的路徑名與路徑屬性不匹配,則返回對象,否則返回空值

matchPath("/users/2", {
  path: "/users/:id",
  exact: true,
  strict: true
});

//  {
//    isExact: true
//    params: {
//        id: "2"
//    }
//    path: "/users/:id"
//    url: "/users/2"
//  }

It returns null when provided pathname does not match path prop.

matchPath("/users", {
  path: "/users/:id",
  exact: true,
  strict: true
});

//  null

f)withRouter

返回目錄

You can get access to the history object’s properties and the closest <Route>'s match via the withRouter higher-order component. withRouter will pass updated match, location, and history props to the wrapped component whenever it renders.
你可以通過 withRouter 高階組件 訪問 history 對象的屬性和最近的<Route>的match。withrouter將在每次render時將更新的match、location和history屬性傳遞給包裝的組件。

import React from "react";
import PropTypes from "prop-types";
import { withRouter } from "react-router";

// A simple component that shows the pathname of the current location
class ShowTheLocation extends React.Component {
  static propTypes = {
    match: PropTypes.object.isRequired,
    location: PropTypes.object.isRequired,
    history: PropTypes.object.isRequired
  };

  render() {
    const { match, location, history } = this.props;

    return <div>You are now at {location.pathname}</div>;
  }
}

// Create a new component that is "connected" (to borrow redux
// terminology) to the router.
const ShowTheLocationWithRouter = withRouter(ShowTheLocation);

Important Note
重要提示

withRouter does not subscribe to location changes like React Redux’s connect does for state changes. Instead, re-renders after location changes propagate out from the <Router> component. This means that withRouter does not re-render on route transitions unless its parent component re-renders.
WithRouter不訂閱location更改,就像React Redux的Connect訂閱state更改一樣。相反,在location更改從<Router>組件傳播出去之後重新渲染。這意味着withrouter不會在路由轉換時重新渲染,除非其父組件重新渲染。

Static Methods and Properties
靜態方法和屬性

All non-react specific static methods and properties of the wrapped component are automatically copied to the “connected” component.
封裝組件的所有非React特定靜態方法和屬性都會自動複製到“已連接”組件。

Component.WrappedComponent

返回目錄

The wrapped component is exposed as the static property WrappedComponent on the returned component, which can be used for testing the component in isolation, among other things.
被包裝的組件暴露爲返回組件上的靜態屬性WrappedComponent ,該組件可用於隔離測試組件等。

// MyComponent.js
export default withRouter(MyComponent)

// MyComponent.test.js
import MyComponent from './MyComponent'
render(<MyComponent.WrappedComponent location={{...}} ... />)

wrappedComponentRef: func

返回目錄

A function that will be passed as the ref prop to the wrapped component.
將作爲ref屬性傳遞給包裝組件的函數。

class Container extends React.Component {
  componentDidMount() {
    this.component.doSomething();
  }

  render() {
    return <MyComponent wrappedComponentRef={c => (this.component = c)} />;
  }
}

5. Hooks

返回目錄

React Router ships with a few hooks that let you access the state of the router and perform navigation from inside your components.

Please note: You need to be using React >= 16.8 in order to use any of these hooks!

  • useHistory
  • useLocation
  • useParams
  • useRouteMatch

useHistory

返回目錄

The useHistory hook gives you access to the history instance that you may use to navigate.

import { useHistory } from "react-router-dom";

function HomeButton() {
  let history = useHistory();

  function handleClick() {
    history.push("/home");
  }

  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  );
}

useLocation

返回目錄

The useLocation hook returns the location object that represents the current URL. You can think about it like a useState that returns a new location whenever the URL changes.

This could be really useful e.g. in a situation where you would like to trigger a new “page view” event using your web analytics tool whenever a new page loads, as in the following example:

import React from "react";
import ReactDOM from "react-dom";
import {
  BrowserRouter as Router,
  Switch,
  useLocation
} from "react-router-dom";

function usePageViews() {
  let location = useLocation();
  React.useEffect(() => {
    ga.send(["pageview", location.pathname]);
  }, [location]);
}

function App() {
  usePageViews();
  return <Switch>...</Switch>;
}

ReactDOM.render(
  <Router>
    <App />
  </Router>,
  node
);

useParams

返回目錄

useParams returns an object of key/value pairs of URL parameters. Use it to access match.params of the current <Route>.

import React from "react";
import ReactDOM from "react-dom";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  useParams
} from "react-router-dom";

function BlogPost() {
  let { slug } = useParams();
  return <div>Now showing post {slug}</div>;
}

ReactDOM.render(
  <Router>
    <Switch>
      <Route exact path="/">
        <HomePage />
      </Route>
      <Route path="/blog/:slug">
        <BlogPost />
      </Route>
    </Switch>
  </Router>,
  node
);

useRouteMatch

返回目錄

The useRouteMatch hook attempts to match the current URL in the same way that a <Route> would. It’s mostly useful for getting access to the match data without actually rendering a <Route>.

Now, instead of

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

function BlogPost() {
  return (
    <Route
      path="/blog/:slug"
      render={({ match }) => {
        // Do whatever you want with the match...
        return <div />;
      }}
    />
  );
}

you can just

import { useRouteMatch } from "react-router-dom";

function BlogPost() {
  let match = useRouteMatch("/blog/:slug");

  // Do whatever you want with the match...
  return <div />;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章