React-Router-Dom 4


安装 react-router-dom

点我返回目录

cnpm i -S react-router-dom

例子

基本/嵌套用法

点我返回目录

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

function BasicExample() {
	return (
		<Router>
			<ul>
				<li><Link to="/">Home</Link></li>
				<li><Link to="/about">About</Link></li>
				<li><Link to="/topics">Topics</Link></li>
			</ul><hr />
			<Route exact path="/" component={Home} />
			<Route path="/about" component={About} />
			<Route path="/topics" component={Topics} />
		</Router>
	);
}
function Home() { return (<div><h2>Home</h2></div>); }
function About() { return (<div><h2>About</h2></div>); }
function Topics({ match }) {
	return (
		<div>
			<ul>
				<li><Link to={'/topics/rendering'}>Rendering</Link></li>
				<li><Link to={'/topics/components'}>Components</Link></li>
			</ul><hr />
			<Route path='/topics/rendering' component={Rendering} />
			<Route path='/topics/components' component={Components} />
			<Route exact path='/topics' render={() => <p>Please select a topic.</p>} />
		</div>
	);
}
function Rendering() { return <p>rendering</p>; }
function Components() { return <p>Components</p>; }

export default BasicExample;
  1. 和 都要包裹在 内
  2. 的作用是在当前位置,当路径(location)与路由路径(path)匹配时,渲染一些UI组件。component属性是要渲染的组件。
  3. Link 就是a标签,其to属性的路径(location)与路由路径(path)所匹配的路由上
  4. 在包裹的组件内也可以定义 Route
  5. Link 的to路径’/topics/rendering’会先匹配上父组件的’/topics’路由和 同组件的’/topics/components’路由,按照匹配顺序渲染相关组件
  6. 如果 路径为’/topics’的 Route 里有 exact 属性的话,Link 的to路径’/topics/rendering’就不会匹配该路由

传递参数/动态路由/模糊匹配

点我返回目录

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

function ParamsExample() {
	return (
		<Router>
			<ul>
				<li><Link to="/order/111">Order/111</Link></li>
				<li><Link to="/order/asc">Order/Asc</Link></li>
			</ul><hr />
			<Route path="/:id" component={Topics} />
			<Route path="/order/:direction(asc|desc)" component={Regex} />
		</Router>
	);
}
function Regex({ match }) { return (<div><h3>Only asc/desc are allowed: {match.params.direction}</h3></div>); }
function Topics({ match }) {
	return (
		<div>
			<ul>
				<li><Link to={`${match.url}/rendering`}>Rendering with React</Link></li>
				<li><Link to={`${match.url}/components`}>Components</Link></li>
			</ul><hr />
			<Route path={`${match.path}/:topicId`} component={Topic} />
			<Route exact path={match.path} render={() => <p>Please select a topic.</p>} />
		</div>
	);
}
function Topic({ match }) { return <p>{match.params.id}->{match.params.topicId}</p>; }

export default ParamsExample;
  1. 当点击 Link 时,会向 Route 传递参数
  2. 其参数 match 里包含路径、参数等相关信息;冒号后面的为参数名
  3. "(asc|desc)"对传入的参数进行正则验证,验证成功则路由匹配。
  4. 根据2获得的信息,可以使用动态路由

重定向

点我返回目录

<Redirect to={{ pathname: "/login", state: { from: props.location } }} />
<Redirect to={pathname} />;

自定义Link

点我返回目录

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

function CustomLinkExample() {
	return (
		<Router><div>
			<OldSchoolMenuLink activeOnlyWhenExact={true} to="/" label="Home" />
			<OldSchoolMenuLink to="/about" label="About" />
			<hr />
			<Route exact path="/" component={Home} />
			<Route path="/about" component={About} />
		</div></Router>
	);
}

function OldSchoolMenuLink({ label, to, activeOnlyWhenExact }) {
	return (
		<Route
			path={to}
			exact={activeOnlyWhenExact}
			children={({ match }) => {
				return <div className={match ? "active" : ""}>
					{match ? "> " : ""}
					<Link to={to}>{label}</Link>
				</div>
			}}
		/>
	);
}

function Home() { return (<div><h2>Home</h2></div>); }
function About() { return (<div><h2>About</h2></div>); }

export default CustomLinkExample;
  1. 自定义路由的children函数,不管匹配与否都会被调用
  2. 匹配的路由 children 的参数为 match;不匹配的路由 children 的参数为 null
  3. 这也可以用于 animations
  4. 和 优先级都高于 。所以不要在使用children的地方使用它们

禁止跳转

点我返回目录

<Prompt
    when={isBlocking}
    message={location =>
        `Are you sure you want to go to ${location.pathname}`
    }
/>

No Match (404)

点我返回目录

<Route component={NoMatch} />
  1. 在 Switch 标签里 会从上往下挨个匹配
  2. 没有匹配路径的Route,放在最下面

递归路径

点我返回目录

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

const PEEPS = [
	{ id: 0, name: "Michelle", friends: [1, 2, 3] },
	{ id: 1, name: "Sean", friends: [0, 3] },
	{ id: 2, name: "Kim", friends: [0, 1, 3] },
	{ id: 3, name: "David", friends: [1, 2] }
];

function find(id) {
	return PEEPS.find(p => p.id == id);
}

function RecursiveExample() {
	return (
		<Router>
			<Person match={{ params: { id: 0 }, url: "" }} />
		</Router>
	);
}

function Person({ match }) {
	let person = find(match.params.id);
	console.log(person)
	return (
		<div><h3>{person.name}'s Friends</h3>
			<ul>
				{person.friends.map(id => (
					<li key={id}>
						<Link to={`${match.url}/${id}`}>{find(id).name}</Link>
					</li>
				))}
			</ul>
			<Route path={`${match.url}/:id`} component={Person} />
		</div>
	);
}
export default RecursiveExample;

Sidebar

点我返回目录

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

const routes = [
	{
		path: "/",
		exact: true,
		sidebar: () => <div>home!</div>,
		main: () => <h2>Home</h2>
	},
	{
		path: "/bubblegum",
		sidebar: () => <div>bubblegum!</div>,
		main: () => <h2>Bubblegum</h2>
	},
	{
		path: "/shoelaces",
		sidebar: () => <div>shoelaces!</div>,
		main: () => <h2>Shoelaces</h2>
	}
];

function SidebarExample() {
    return (
        <Router>
            <div style={{ display: "flex" }}>
            	<div style={{ padding: "10px", width: "40%", background: "#f0f0f0" }}>
            		<ul style={{ listStyleType: "none", padding: 0 }}>
            			<li><Link to="/">Home</Link></li>
            			<li><Link to="/bubblegum">Bubblegum</Link></li>
            			<li><Link to="/shoelaces">Shoelaces</Link></li>
            		</ul>
            		{routes.map((route, index) => (
            			<Route key={index} path={route.path} exact={route.exact} component={route.sidebar}/>
            		))}
            	</div>
            	<div style={{ flex: 1, padding: "10px" }}>
            		{routes.map((route, index) => (
            			<Route key={index} path={route.path} exact={route.exact} component={route.main}/>
            		))}
            	</div>
            </div>
        </Router>
    );
}
export default SidebarExample;

动画转换

点我返回目录

路由配置

点我返回目录

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

function Sandwiches() { return <h2>Sandwiches</h2>; }
function Tacos({ routes }) {
	return (
		<div>
			<h2>Tacos</h2>
			<ul>
				<li><Link to="/tacos/bus">Bus</Link></li>
				<li><Link to="/tacos/cart">Cart</Link></li>
			</ul>
			{routes.map((route, i) => (
				<RouteWithSubRoutes key={i} {...route} />
			))}
		</div>
	);
}
function Bus() { return <h3>Bus</h3>; }
function Cart() { return <h3>Cart</h3>; }

///////////////////////////
const routes = [
	{
		path: "/sandwiches",
		component: Sandwiches
	},
	{
		path: "/tacos",
		component: Tacos,
		routes: [
			{
				path: "/tacos/bus",
				component: Bus
			},
			{
				path: "/tacos/cart",
				component: Cart
			}
		]
	}
];

function RouteWithSubRoutes(route) {
	return (
		<Route
			path={route.path}
			render={props => (
				<route.component {...props} routes={route.routes} />
			)}
		/>
	);
}

function RouteConfigExample() {
	return (
		<Router>
			<div>
				<ul>
					<li><Link to="/sandwiches">Sandwiches</Link></li>
					<li><Link to="/tacos">Tacos</Link></li>
				</ul>
				{routes.map((route, i) => (
					<RouteWithSubRoutes key={i} {...route} />
				))}
			</div>
		</Router>
	);
}
export default RouteConfigExample;

模式库

点我返回目录

静态路由上下文

点我返回目录

查询参数

点我返回目录

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

//组件
import Home from './components/Home';
import News from './components/News';

class Topics extends React.Component {
    constructor(props) {
        super(props);
        this.state = {}
    }
    render() {
        return (
            <div>
                <h2>2级路由</h2>
                <Link to={`${this.props.match.url}/rendering`}>Rendering with React</Link>
                <Link to={`${this.props.match.url}/components`}>Components</Link>
                <Link to={`${this.props.match.url}/props-v-state`}>Props v. State</Link>
                <Link to="/home">Home</Link>
                <Route path={`${this.props.match.path}/:topicId`} component={Topic} />
                <Route exact path={this.props.match.path} render={() => <h3>Please select a topic.</h3>} />
            </div >
        );
    }
}

function Topic({ match }) {
    return (
        <div>
            <h3>{match.params.topicId}</h3>
        </div>
    );
}

//入口
class App extends Component{
    render(){
        return (
            <Router>
                <div className="App">
                    <h1>1级路由</h1>
                    //路由
                    <Route exact path="/" />
                    <Route path="/home" component={Home} />
                    <Route path="/news" component={News} />
                    //跳转
                    <Link to="/">路由页</Link>
                    <Link to="/home">Home</Link>
                    <Link to="/news">News</Link>
                    
                    <h2>2级路由</h2>
                    <div>
                        <Link to={`${match.url}/rendering`}>Rendering with React</Link>
                        <Link to={`${match.url}/components`}>Components</Link>
                        <Link to={`${match.url}/props-v-state`}>Props v. State</Link>
                    </div>
                </div>
            </Router>
        )
    }
}

API

点我返回目录

使用HTML5历史记录API(PushState、ReplaceState和PopState事件)保持用户界面与URL同步的。

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对话框。默认使用window.confirm.
// this is the default behavior
function getConfirmation(message, callback) {
  const allowTransition = window.confirm(message);
  callback(allowTransition);
}

<BrowserRouter getUserConfirmation={getConfirmation} />;

forceRefresh

点我返回目录

  • 类型:bool
  • 说明:如果为真,路由器将在页面导航中使用整页刷新。您可能只希望在不支持HTML5历史记录API的浏览器中使用它
const supportsHistory = 'pushState' in window.history
<BrowserRouter forceRefresh={!supportsHistory} />

keyLength

点我返回目录

  • 类型:number
  • 说明:location.key的长度。默认为6
<BrowserRouter keyLength={12} />

children

点我返回目录

  • 类型:node|
  • 说明:A single child element to render.

点我返回目录

使用URL的哈希部分(即window.location.hash)保持用户界面与URL同步的。

重要提示:哈希历史不支持location.key或location.state。任何需要此行为的代码或插件都无法工作。由于此技术仅用于支持传统浏览器,因此我们建议您将服务器配置为使用

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

<HashRouter>
  <App/>
</HashRouter>

basename

点我返回目录

  • 类型:string
  • 说明:所有位置的基本URL。格式正确的basename应该有一个前导斜杠,但不能有尾随斜杠。
<HashRouter basename="/calendar"/>
<Link to="/today"/> // renders <a href="#/calendar/today">

getUserConfirmation

点我返回目录

  • 类型:func
  • 说明:这个函数用于confirm对话框。默认使用window.confirm.
// this is the default behavior
function getConfirmation(message, callback) {
  const allowTransition = window.confirm(message);
  callback(allowTransition);
}

<HashRouter getUserConfirmation={getConfirmation} />;

hashType

点我返回目录

  • 类型:string
  • 说明:用于window.location.hash的编码类型。可用值为:
    • “slash” - Creates hashes like #/ and #/sunshine/lollipops (默认)
    • “noslash” - Creates hashes like # and #sunshine/lollipops
    • “hashbang” - Creates “ajax crawlable” (deprecated by Google) hashes like #!/ and #!/sunshine/lollipops

children

点我返回目录

  • 类型:node
  • 说明:A single child element to render.

to

点我返回目录

  • 类型:string
  • 说明:要链接到的位置的字符串表示形式,通过连接位置的路径名、搜索和哈希属性创建。
    <Link to="/courses?sort=name" />
    
  • 类型:object
  • 说明:可以具有以下任何属性的对象:
    • pathname:表示要 link 到的路径的字符串
    • search:查询参数的字符串表示
    • hash:放在URL中的哈希,例如A-hash
    • state:保留到该位置的状态
    <Link
      to={{
        pathname: "/courses",
        search: "?sort=name",
        hash: "#the-hash",
        state: { fromDashboard: true }
      }}
    />
    
  • 类型:function
  • 说明:当前 location 作为参数传递给该函数,该函数应以字符串或对象的形式返回位置表示。
    <Link to={location => ({ ...location, pathname: "/courses" })} />
    <Link to={location => `${location.pathname}?sort=name`} />
    

replace

点我返回目录

  • 类型:bool
  • 说明:如果为真,单击链接将替换历史堆栈中的当前条目,而不是添加新条目。
<Link to="/courses" replace />

innerRef

点我返回目录

  • 类型:function
  • 说明:允许访问组件的基础引用
    const refCallback = node => {
        // `node` refers to the mounted DOM element or null when unmounted
    }
    
    <Link to="/" innerRef={refCallback} />
    
  • 类型:RefObject
  • 说明:使用React.createRef()获取组件的基础引用
    const anchorRef = React.createRef()
    
    <Link to="/" innerRef={anchorRef} />
    

others

点我返回目录

You can also pass props you’d like to be on the such as a title, id, className, etc.

点我返回目录

的特殊版本,它将在与当前URL匹配时向呈现元素添加样式属性。

activeClassName

点我返回目录

  • 类型:string
  • 说明:当元素处于活动状态时提供该元素的类。默认的给定类是活动的。这将与classname属性结合在一起。
<NavLink to="/faq" activeClassName="selected">
  FAQs
</NavLink>

activeStyle

点我返回目录

  • 类型:object
  • 说明:活动时应用于元素的样式。
<NavLink
  to="/faq"
  activeStyle={{
    fontWeight: "bold",
    color: "red"
  }}
>
  FAQs
</NavLink>

exact

点我返回目录

  • 类型:bool
  • 说明:如果为true,则仅当位置完全匹配时才应用活动类/样式
<NavLink exact to="/profile">
  Profile
</NavLink>

strict

点我返回目录

  • 类型:bool
  • 说明:如果为true,则在确定位置是否与当前URL匹配时,将考虑位置路径名的尾随斜杠。请参阅文档。
<NavLink strict to="/events/">
  Events
</NavLink>

isActive

点我返回目录

  • 类型:func
  • 说明:用于添加额外逻辑以确定链接是否处于活动状态的函数。如果您想做的不仅仅是验证 Link 的 pathname 是否与当前 URL 的 pathname 匹配,那么应该使用此选项。
// only consider an event active if its event id is an odd number
const oddEvent = (match, location) => {
  if (!match) {
    return false
  }
  const eventID = parseInt(match.params.eventID)
  return !isNaN(eventID) && eventID % 2 === 1
}

<NavLink
  to="/events/123"
  isActive={oddEvent}
>Event 123</NavLink>

location

点我返回目录

  • 类型:object
  • 说明:isActive 比较当前历史 location (通常是当前的 browser URL)。要与其他 location 进行比较,可以传递一个 location

aria-current

点我返回目录

  • 类型:string
  • 说明:活动链接上使用的 aria-current 属性的值。可用值为:
    • “page” - 默认。用于指示一组分页链接中的link
    • “step” - 用于指示基于步骤的流程的步骤指示器中的link
    • “location” - 用于指示视觉上突出显示为流程图当前 component 的 image
    • “date” - 用于指示日历中的当前日期
    • “time” - 用于指示时间表中的当前时间
    • “true” - 用于指示导航链接是否处于活动状态

点我返回目录

用于在离开页面前提示用户。当您的应用程序进入一个应该阻止用户导航的状态时(就像一个表单被填了一半),请呈现一个。

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?" />

点我返回目录

将“url”的历史记录保存在内存中的(不读取或写入地址栏)。适用于测试和非浏览器环境,如React Native。

import { MemoryRouter } from 'react-router'

<MemoryRouter>
  <App/>
</MemoryRouter>

initialEntries

点我返回目录

  • 类型:array
  • 说明:历史堆栈中的位置数组。这些可能是具有{ pathname, search, hash, state } 或简单字符串URL的完整 location objects。
<MemoryRouter
  initialEntries={["/one", "/two", { pathname: "/three" }]}
  initialIndex={1}
>
  <App />
</MemoryRouter>

initialIndex

点我返回目录

  • 类型:number
  • 说明:初始项数组中初始位置的索引。

getUserConfirmation

点我返回目录

  • 类型:func
  • 说明:用于确认导航的功能。在直接使用和时,必须使用此选项。

keyLength

点我返回目录

  • 类型:number
  • 说明:The length of location.key. Defaults to 6.
<MemoryRouter keyLength={12} />

children

点我返回目录

  • 类型:node
  • 说明:A single child element to render.

点我返回目录

渲染将导航到新位置。新位置将覆盖历史堆栈中的当前位置,如服务器端重定向(HTTP 3xx)所做的操作。

import { Route, Redirect } from 'react-router'

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

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 from='/old-path' to='/new-path'/>
  <Route path='/new-path' component={Place}/>
</Switch>

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

exact/strict/sensitive

点我返回目录

点我返回目录

路由组件可能是反应路由器中理解和学习良好使用的最重要组件。它最基本的职责是在位置与路由路径匹配时呈现一些UI。
考虑以下代码:

import { BrowserRouter as Router, Route } from 'react-router-dom'

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

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>

react empty”注释只是react的空呈现的实现细节。但就我们的目的而言,这是有指导意义的。一个路由在技术上总是“渲染”,即使其渲染为空。一旦应用程序位置与路由路径匹配,就会呈现组件。

路由渲染的方式

点我返回目录

一个有三种方式来渲染:

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.

每一种都在不同的情况下有用。在给定的上应该只使用其中一种属性。请参阅下面他们的解释,了解您为什么有3个选项。大多数情况下,您将使用component。

路由的参数

点我返回目录

所有的三种渲染方式将会接收到同样的三个路由参数

  • match
  • location
  • history

component

点我返回目录

A React component to render only when the location matches. It will be rendered with route props.


仅当位置匹配时才渲染的 React 组件。它将使用路由参数渲染。

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

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

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)。

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

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

<FadingRoute path="/cool" component={Something}/>

Warning: takes precedence over so don’t use both in the same .

警告:优先于,因此不要在同一中同时使用这两者。

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。这里,如果路由匹配,我们将添加一个活动类

<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>
    )}
  />
);

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: Both and take precedence over so don’t use more than one in the same .


警告:和都优先于,因此不要在同一中使用多个。

path

点我返回目录

  • 类型:string | string[]
  • 说明:被path-to-regexp@^1.7.0 理解的任何有效的URL路径或路径数组
<Route path="/users/:id" component={User} />
<Route path={["/users/:id", "/profile/:id"]} component={User} />

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" component={About} />
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/" component={About} />
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" component={About} />
path location.pathname matches?
/one/ /one yes
/one/ /one/ no
/one/ /one/two no

location

点我返回目录

  • 类型:object

A 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 to a location other than the current history location, as shown in the Animated Transitions example.


这在需要将匹配到当前历史位置以外的位置时非常有用,如动画转换示例中所示。

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


如果一个元素包装在一个 中,并且与传递给 的位置(或当前历史位置)匹配,那么传递给的位置属性将被 使用的属性覆盖(此处给出)。

sensitive

点我返回目录

  • 类型:bool
  • 说明:When true, will match if the path is case sensitive.
    如果为true,则在路径区分大小写时匹配。
<Route sensitive path="/one" component={About} />
path location.pathname sensitive matches?
/one /one true yes
/One /one true no
/One /one false yes

点我返回目录

The common low-level interface for all router components. Typically apps will use one of the high-level routers instead:


所有路由器组件的通用低级接口。通常,app将使用高级路由器之一:

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 { Router } from "react-router";
import { createBrowserHistory } from "history";

const history = createBrowserHistory()

<Router history={history}>
  <App/>
</Router>

history

点我返回目录

  • 类型:object
  • 说明:A history object to use for navigation.
    用于导航的历史记录对象。
import { createBrowserHistory } from "history";

const customHistory = createBrowserHistory();

<Router history={customHistory} />;

children

点我返回目录

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

点我返回目录

A 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 { createServer } from "http";
import React from "react";
import ReactDOMServer from "react-dom/server";
import { StaticRouter } from "react-router";

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.

点我返回目录

Renders the first child or that matches the location.


渲染 第一个与位置匹配的子级或。

How is this different than just using a bunch of s?


这与使用一组有什么不同?

is unique in that it renders a route exclusively. In contrast, every that matches the location renders inclusively. Consider this code:


是唯一的,因为它只渲染路由。与此相反,与位置匹配的每个都包含在内。考虑此代码:

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

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 { 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>

Now, if we’re at /about, will start looking for a matching . will match and will stop looking for matches and render . Similarly, if we’re at /michael then will render.


现在,如果我们是/about, 将开始寻找匹配的。将匹配, 将停止查找匹配项并渲染。同样,如果我们是/michael,那么将被渲染。

This is also useful for animated transitions since the matched is rendered in the same position as the previous one.


这对于动画转换也很有用,因为匹配的与前一个位置渲染在同一位置。

<Fade>
  <Switch>
    {/* there will only ever be one child here */}
    <Route/>
    <Route/>
  </Switch>
</Fade>

<Fade>
  <Route/>
  <Route/>
  {/* there will always be two children here,
      one might render null though, making transitions
      a bit more cumbersome to work out */}
</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 should be or elements. Only the first child to match the current location will be rendered.


的所有子元素都应该是或元素。将只呈现与当前位置匹配的第一个子级。

elements are matched using their path prop and elements are matched using their from prop. A with no path prop or a with no from prop will always match the current location.


元素使用其路径属性匹配,而元素使用其from属性匹配。没有路径道具的或没有from道具的将始终匹配当前位置。

When you include a in a , it can use any of the 's location matching props: path, exact, and strict. from is just an alias for the path prop.


当您在 中包含时,它可以使用任何的位置匹配属性:path、exact和strict。from只是路径属性的别名。

If a location prop is given to the , it will override the location prop on the matching child element.


如果为 提供了location属性,它将覆盖匹配子元素上的location属性。

<Switch>
  <Route exact path="/" component={Home} />

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

  <Route component={NoMatch} />
</Switch>

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 , not from history.location. This ensures your assumptions about React are correct in lifecycle hooks. For example:


history对象是可变的。因此,建议从的渲染属性访问位置,而不是从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文档。

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:


路由器将在几个地方为您提供一个位置对象:

  • as this.props.location
  • as ({ location }) => ()
  • 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
  • Native
  • 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.


这将阻止他们使用路由器状态下的实际位置。这对于动画和挂起的导航很有用,或者在任何时候您想要欺骗一个组件,使其在与真实组件不同的位置进行渲染。

match

A match object contains information about how a 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 s
    用于匹配的路径模式。用于构建嵌套的s
  • url - (string) The matched portion of the URL. Useful for building nested s
    URL的匹配部分。用于构建嵌套的s

You’ll have access to match objects in various places:


您可以在不同位置访问match对象

  • as this.props.match
  • as ({ match }) => ()
  • 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 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 's contents when it does match can be useful, but certain challenges arise from this situation.


即使路由的路径与当前位置不匹配,使用子属性的也将调用其children函数。在这种情况下,match将为空。当匹配时能够渲染的内容是有用的,但是这种情况会带来一些挑战。

The default way to “resolve” URLs is to join the match.url string to the “relative” path.


“解析”URL的默认方法是将match.url字符串连接到“relative”路径

`${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 when using the children prop.


如果在match为空时尝试执行此操作,则将以类型错误结束。这意味着当使用children prop时,尝试连接内的“相对”路径是不安全的。

A similar, but more subtle situation occurs when you use a pathless inside of a that generates a null match object.


当在生成空match对象的内部使用无路径的时,会出现类似但更微妙的情况。

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

Pathless 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.


无路径的s从其父对象继承其match对象。如果他们的父match为空,那么他们的match也将为空。这意味着a)任何routes/links都必须是绝对的,因为没有要解析的父路由;b)父match可以为空的无路径路由需要使用children属性进行渲染。

matchPath

点我返回目录

This lets you use the same matching code that uses except outside of the normal render cycle, like gathering up data dependencies before rendering on the server.


这允许您使用与使用的相同的匹配代码,除了正常渲染周期之外,例如在服务器上渲染之前收集数据依赖项。

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

点我返回目录

如果提供的路径名与路径属性不匹配,则返回对象,否则返回空值

withRouter

点我返回目录

You can get access to the history object’s properties and the closest '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 对象的属性和最近的的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 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更改从组件传播出去之后重新渲染。这意味着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)} />;
  }
}
发布了33 篇原创文章 · 获赞 2 · 访问量 2014

猜你喜欢

转载自blog.csdn.net/wwwmewww/article/details/102557924