React Router API

API

BrowserRouter

底层调用H5的history api

basename: string

所有路由的基本url。设置时只需要前导斜杠,不需要尾部斜杠

<BrowserRouter basename="/calendar" />
<Link to="/today"/> // renders <a href="/calendar/today">

getUserConfirmation: func

默认调用 window.confirm显示一个模态对话框

forceRefresh: bool

是否在路由跳转时强制刷新页面,可能只需要在不支持H5 history 的前提下使用这个属性

keyLength: number

location.key的长度,默认为6

children: node

需要渲染的子元素

HashRouter

调用hash api

注意:无法使用location.key 或者 location.state属性

basename: string | getUserConfirmation: func | children: node

同BrowserRouter

hashType: string

为应用提供可声明,可访问性的导航

to:string | object | function

字符串形式

<Link to="/courses?sort=name" />

对象形式

  • pathname: A string representing the path to link to.
  • search: A string representation of query parameters.
  • hash: A hash to put in the URL, e.g. #a-hash.
  • state: State to persist to the location.
<Link
  to={{
    pathname: "/courses",
    search: "?sort=name",
    hash: "#the-hash",
    state: { fromDashboard: true }
  }}
/>

函数形式

参数为当前location,返回值为对象或字符串

<Link to={location => ({ ...location, pathname: "/courses" })} />
<Link to={location => `${location.pathname}?sort=name`} />

replace:bool

替换history stack 而不是添加一个

<Link to="/courses" replace />

innerRef: function | RefObject

使用React.createRef()获取组件的底层引用

others

自定义其他属性,例如title,id,className

Link的特殊版本,它将在与当前URL匹配时为渲染元素添加样式属性。

activeClassName:string

激活时命中的样式,默认为样式名为active,该属性会与className属性提供的样式合并

activeStyle:object

<NavLink
  to="/faq"
  activeStyle={{
    fontWeight: "bold",
    color: "red"
  }}
>
  FAQs
</NavLink>

exact:bool

是否默认选中

strict:bool

在命中路由时是否考虑尾部斜杠

isActive:func

激活时调用的函数,包含match和location两个参数

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

当前的历史记录位置。要比较不同的location,可以将当前location作为参数传入

aria-current:string

语义化

Prompt

用于在离开当前导航时提示用户

message:string | func

<Prompt
  message={location =>
    location.pathname.startsWith("/app")
      ? true
      : `Are you sure you want to go to ${location.pathname}?`
  }
/>

when: bool

控制prompt的渲染时机

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

MemoryRouter

将用户的访问记录存储在内存中。适合于测试或无浏览器环境如react native

initialEntries: array

初始化一个location对象的集合。location可以是一个包含{pathname,search,hash,state}中任意属性的对象或字符串

<MemoryRouter
  initialEntries={["/one", "/two", { pathname: "/three" }]}
  initialIndex={1}
>
  <App />
</MemoryRouter>

initialIndex: number

指定初始化initialEntries的下标

getUserConfirmation: func | keyLength: number | children: node

类似BrowerRouter

Redirect

在history stack中,redirect-to 的 location 将会替换当前的 location

to:string | object

<Redirect
  to={{
    pathname: "/login",
    search: "?utm=your+face",
    state: { referrer: currentLocation }
  }}
/>

state 参数可以在redirected-to 组件的this.props.location.state中访问到

push: bool

如果设置为true,将不会替换history stack中的location

from: string

exact:bool

strict:bool

sensitive:bool

是否大小写敏感

Route

当location命中时,去渲染对应的组件

component

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

function User({match, location, history}){};

底层调用React.createElement去创建一个新的React element

render:func

函数同样可以访问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}/>

注意:component的优先级高于render

children:func

它工作的方式同render一样,区别在于不管有没有命中路由,他都将被渲染

children 接受的参数与component和render相同,当路由没有命中的时候,match为null

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

注意:component和render的优先级高于children, 应当只使用其中的一个元素

path:string | string[]

<Route path="/users/:id" component={User} />
<Route path={["/users/:id", "/profile/:id"]} component={User} />

exact:bool

strict:bool

具有尾部斜杠的路径将仅匹配具有尾部斜杠的location.pathname。当location.pathname中有其他URL段时,这不起作用。

path location.pathname matches?
/one/ /one no
/one/ /one/ yes
/one/ /one/two yes

sensitive:bool

path location.pathname sensitive matches?
/one /one true yes
/One /one true no
/One /one false yes

location:object

Router

所有路由器组件的通用低级接口

history:object

children:node

StaticRouter

永远不会改变location的Router

basename: string

location: string | object

context: object

在渲染期间,组件可以向对象添加属性以存储有关渲染的信息。

<Route>匹配时,它会将context渲染为staticContext prop传递给命中的组件

渲染后,context中的属性可用于配置服务器的响应。

children: node

Switch

渲染第一个匹配的Route或Redirect

Switch与一组Route的区别在于,它仅仅渲染第一个匹配的路由

location: object

children: node

Switch只能包含Route和Redirect元素,Route匹配path元素,Redirect匹配from元素,仅匹配其中一个元素

history

React Router的两个主要依赖项之一https://github.com/ReactTraining/history

history is mutable

因为history是不可变的。因此建议从Router的渲染props来访问location而不是通过history.location来访问

location

location代表应用程序现在的位置,您希望它去的位置,甚至是当前的位置。看起来像这样:

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

你可以通过这些方式访问location:

history.location同样也可访问到location,但最好不要这样做,因为history是不可变的

location对象是never mutated,所以当导航改变的时候,你可以在组件的生命周期钩子中访问它,以决定是否进行动画渲染或获取数据等操作

最后,你可以通过把location传递给:

这将阻止他们使用路由器状态中的实际位置。这对于动画和待定导航很有用,或者您想要将组件欺骗渲染到与真实位置不同的位置时

match

match对象包含如下属性:

  • params - (object) Key/value pairs parsed from the URL corresponding to the dynamic segments of the path
  • isExact - (boolean) true if the entire URL was matched (no trailing characters)
  • path - (string) The path pattern used to match. Useful for building nested <Route>s
  • url - (string) The matched portion of the URL. Useful for building nested <Link>s

你可以通过如下方式去访问它:

null match

注意:当你在Route上使用children属性渲染,并试图访问match.url属性时,可能会出现一个TypeError错误

matchPath

这使您可以使用Route使用的相同匹配代码,但你可以在正常渲染周期之外使用它

第一个参数pathname,你需要命中的路由。

第二个参数为一个对象,他们与Route接受的匹配props相同

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

返回值,当匹配成功时返回一个object,当匹配失败时返回null

withRouter

您可以通过withRouter高阶组件访问history的属性和最近的Route的match对象

posted @ 2019-08-26 17:36  CodingSherlock  阅读(442)  评论(0编辑  收藏  举报