react-router 第3版 和 第4版 有较大的区别。

两个版本都需要掌握,一方面便于维护旧代码,另一方面紧跟趋势。

react router 4.x版为动态路由。4.x版本之前为静态路由。


react-router 4.x API

<BrowserRouter>

使用HTML5 History API 来保持URL和UI的同步。

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

<BrowserRouter
    basename = {optionalString}
    forceRefresh = {optionalBoolen}
    gerUserConfirmation = {optionalFunc}
    keyLength = {optionalNumber}
>
    <App/>
</BrowserRouter>
  • basename :string,设置基准URL,其子router将基于此基准URL。格式:需由一个前导斜杠,但是不能有尾部斜杠。
<BrowserRouter basename='/calendar'>
    <Link to="/today"> // renders <a href="/calendar/today">
  • getUserConfirmation :func,用于确认是否需要导航,默认使用window.confirm。

  • forceRefresh :bool,若为true,则在导航时整个页面会刷新,一般只用在不支持H5 History API 的浏览器。

  • keyLength :number,用于限制location.key的长度,默认为6.

  • children :node

<HashRouter>

使用URL的hash部分(window.location.hash)来保持UI和URL的同步。

注意:hash 历史导航不支持location.key 和 location.state。这项技术仅用于支持老旧浏览器,对于现代浏览器推荐使用<BrowserRouter>

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

<HashRouter basename="calendar" hashType="slash">
    <Link to="/today" /> //renders <a href="#/calendar/today">
</HashRouter>
  • basename,同<BrowserRouter>
  • getUserConfirmation,同<BrowserRouter>
  • hashType:string,window.location.hash使用的类型,有如下3中合法的值:

  • slash:后面跟一个斜杠,形式为 #/sunshine/lollipops,这也是默认的形式

  • noslash:后面没有斜杠,形式为 #sunshine/lollipops

  • hashbang:形式为 #!/sunshine/lollipops

  • children:node

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

import { Link } from 'react-router-dom';

<Link to="/about">About</Link>
  • to:string,字符串形式的链接地址,通过location的pathname,search,hash属性建立
<Link to="/courses?sort=name"/>
  • to : object,对象形式的链接地址,可以包含如下属性

  • pathname

  • search : 查询参数

  • hash

  • state : 存储到location中的额外数据

<Link to={{
    pathname:'/courses',
    search:'?sort=name',
    hash:'#the-hash',
    state:{
        fromDashboard:true
    }
}}/>
  • replace : bool,但设置为true时,点击链接后将替换历史堆栈中的当前条目,而不是添加新条目。默认为false
<Link to="/courses" replace/>
  • innerRef:func,允许访问组件的底层引用
const refCallback = node => {
    //node 指向最终挂载的DOM元素,在卸载时为 null
}
<Link to='/' innerRef={refCallback} />
  • others ,其他如title,id,className 属性等

特殊版<Link>,会在匹配当前URL时,为其呈现元素添加样式属性。

import { NavLink } from 'react-router-dom';
<NavLink to="/about">About</NavLink>
  • activeClassName : string,当元素处于激活状态时的class,默认为active。
  • activeStyle : object,元素处于激活状态时应用的样式。
  • exact :bool,若为true,则以上两条属性只有在location完全匹配时生效。
  • strict : bool,当为true时,location's pathnane尾部的斜杠也将被拿来与location进行对比,以确定URL是否匹配。
  • isActive :func,添加额外逻辑已确定链接是否是active,当你需要做路径名与当前URL路径名匹配之外的跟多验证是,需要用到isActive。
  • location : object,isActive 默认比较的是当前历史位置(通常是浏览器当前的url),可以通过location属性传递一个不同的位置进行比较。

<Prompt>

用于在页面跳转之前给用户确认信息。当应用程序处于某种状态时(如填写了一般的表单)应该阻止用户跳转,这是需要用到<Prompt>.

import { Prompt } from 'react-router';

<Prompt>
    when={formIsHalfFilledOut}
    message="Are you sure you want to leave?"
/>
  • message : string,当将跳转时给用户的提示信息
  • message : func,用户提示信息的func版,参数为next location(即将跳转的地址)
<Prompt message={location=>(
    location.pathname.startWith('/app')
    ?true
    :`Are you sure you want to go to ${location.pathname}?`
)}>
  • when :bool,在应用中可以不必根据条件来渲染<Prompt>组件,可以始终渲染<Prompt>组件,然后通过设置when属性值以允许或者阻止相应的导航。

<MemoryRouter>

将URL history 保存在内存中(不读写地址栏),在测试或者非浏览器环境(react native)中会很有用。

import { MemoryRouter } from 'react-router';

<MemoryRouter 
    initialEntries = {['/one','/two',{pathname:'/three'}]}
    initialIndex = {1}
>
    <App/>
</MemoryRouter>
  • initialEntries : array,历史堆栈中的一些位置组成的数组。可以是包含{pathname,search,hash,state}的完整位置对象或仅仅是一个简单的URLs 字符串。
  • initialIndex :number,initialEntries数组中的初始索引位置。
  • getUserConfirmation
  • keyLength
  • children

<Redirect>

<Redirect> 一般会导航到一个新的位置。新的位置将替换History stack 中的当前条目,就像服务器端的重定向一样。

import {Router, Redirect} from 'react-router';
<Router exact path="/" render={()=>(
    loggedIn?(<Redirect to="/dashboard">)
    :(<PublicHomePage/>)
)}>
  • to :string,所有要使用的 URL 参数必须由from提供
  • to :object
  • push :bool,当为true,重定向回想新的位置推入History stack,而不是替代当前的条目。
  • from :string,要重定向的路径名。所有匹配的URL参数都将会提供给to,必须包含在to中用到的所有参数,to 未能使用的其他参数将被忽略。一般只用在<Switch>组件内。
<Switch>
    <Redireact from="/old-jpath" to="/new-path"/>
    <Route path="/new-path" component={Place}/>
<Switch>
  • exact :bool
  • strict :bool

<Route>

react-router 中最重要的组件。其基本职责是在其path属性和某个location匹配时呈现对应的UI。

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

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

Route render method :使用<Route>渲染内容的3种方式

  1. <Route component>
  2. <Route render>
  3. <Route children>

Route props : 三种渲染方式提供三个相同的路由属性

  1. match
  2. location
  3. history

  4. component :只有当位置匹配时才会渲染react 组件,该组件会接受Route props 作为属性。

const User = ({match}) => {
    return <h1> hello {match.params.username}!</h1>;
}
<Route path="/user:username" component={User} />

当使用 component 时,Router 将根据指定的组件,使用React.createElement 创建一个新的React元素。这意味着若向component提供一个内联函数,那么每次渲染都会创建一个新的组件。(这会造成浪费)。当使用内联函数进行渲染时,建议使用render或者children。

  • render :func,利用render可以方便的进行内联渲染和包装。
//convenient inline rendering
<Route path="/home" render={()=> <div>Home</home>}>

//wrapping/composing
const FadingRoute = ({component:Component,...rest}) => (
    <Route {...rest} render={props=>(
        <FadeIn>
            <Component {...props}/>
        </FadeIn>
    )}/>
)
<FadingRoute path="/cool" component={something} />

注意:<Route component> 的优先级高于 <Route render>,因而不要在同一个<Route>中使用两者。

  • children :func,有时不论位置是否匹配都想渲染一些内容,这是可以使用children属性。除了不论是否匹配都会被调用外,它的工作原理和render完全一样。
const ListItemLink = ({to,...rest})=>(
    <Route path={to} children={({match})=>(
        <li className={match?'active':''}>
            <Link to={to} {...rest} />
        </li>
    )}/>
)
<ul>
    <ListItemLink to="/somewhere" />
    <ListItemLink to="somewhere-else" />
</ul>

注意:<Route component><Route render>优先于<Route children>

  • path :string
  • exact :bool
  • strict :bool

strict 的额外说明

results matching ""

    No results matching ""