React学习之React路由机制

React 路由机制

注意:react-router是3.x的版本,我们使用的是4.+版本,使用的是react-router-dom

安装react-router-domyarn add react-router-dom --save

目前react-router-dom已经是 5.2.0版本。

路由组件(作为根组件)

1. BrowserRouter

一个使用HTML5 history API( pushStatereplaceStatepopstate事件)来保持UI和URL同步的Router组件。

<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">
    <Link to="/tomorrow"/> // renders <a href="/calendar/tomorrow">
    ...
</BrowserRouter>
getUserConfirmation: func

作用:导航到此页面前执行的函数,默认使用 window.confirm(对话确认框)

<BrowserRouter
  getUserConfirmation={(message, callback) => {
    // this is the default behavior
    const allowTransition = window.confirm(message);
    callback(allowTransition);
  }}
/>
forceRefresh: bool

作用:当浏览器不支持 HTML5 的 history API 时强制刷新页面。

const supportsHistory = 'pushState' in window.history
<BrowserRouter forceRefresh={!supportsHistory} />
keyLength: number

作用:设置它里面路由的 location.key 的长度。默认是6。(key的作用:点击同一个链接时,每次该路由下的 location.key都会改变,可以通过 key 的变化来刷新页面。)

<BrowserRouter keyLength={12} />

2. HashRouter

一个使用URL的hash部分(即window.location.hash)来保持UI和URL的同步的Router组件。

重要说明:Hash history不支持location.keylocation.state。在以前的版本中,我们尝试对行为进行匀称处理,但存在一些无法解决的极端情况。任何需要此行为的代码或插件都将无法工作。由于此技术仅旨在支持旧版浏览器,因此我们建议您配置服务器以供使用<BrowserHistory>

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

路径匹配组件

1. Route

它最基本的职责是在其 path 属性与某个 location 匹配时呈现一些 UI。

<Route path='/home' component={Home}></Route>
2. Redirect

重定向,可以跳到想要的组件中

<Redirect exact from="/" to="/student"></Redirect>
3. Switch

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

<Switch>
  <Route exact path="/">
    <Home />
  </Route>
  <Route path="/about">
    <About />
  </Route>
  <Route path="/user">
    <User />
  </Route>
</Switch>

导航组件

1. Link

Link 组件最终会渲染为 a标签,使用to参数来描述需要定位的页面。

<Link to="/about">About</Link>
2. NavLink

<Link>的一个特定版本,会在匹配上当前的url的时候给已经渲染的元素添加参数。

activeClassName: string

元素处于活动状态时提供的类。给定的默认类为active

<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时,则pathname在确定位置是否与当前URL匹配时,将考虑位置pathname后的斜线。

<NavLink strict to="/events/">
  Events
</NavLink>
isActive: func

判断链接是否激活的额外逻辑的功能。

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

history API跳转

在组件中通过this.props.history控制路由的改变。

在组件中引入withRouter来访问history

通过push方法调到指定组件,参数:

  1. 路径:this.props.history.push('/content') 将新的路径压入到history中

  2. 传递一个对象,路径放在pathname中,可传递参数state

this.props.history.push({
   pathname:'/student',
   state:record
})
componentDidMount() {
   console.log(this.props.location.state);
}

这种方式跳转可以通过 this.props.location.state 来获取传递的参数

特别的,将参数放在state中可以防止刷新页面后数据丢失

  • this.props.history的其他方法

this.props.history.go(n) n为正数或者负数,表示前进或者后退

this.props.history.goBack() 后退

this.props.history.goForward() 前进

React 路由跳转

1. API跳转

this.props.history.push('/course')

2. NavLink

<NavLink to="/course"></NavLink>

3. Link

<Link to="/course"></Link>

4. a标签

<a href="#/course"></a>

React 路由传参

1. API传参

放在state中传递可以防止页面刷新数据丢失

this.props.history.push({
    pathname: "/course",
    state: {name: 'tom'}
})
//获取
componentDidMount() {
   console.log(this.props.location.state);
}
2. 查询字符串传参
<NavLink to="/course?name=tom">NavLink跳转</NavLink>
//获取
componentDidMount() {
   console.log(this.props.location.search);//?name=tom
}
3. 动态路由传参
<Route path="/sc/:id" component={Course}></Route>

<NavLink to="/sc/2">NavLink跳转-动态路由</NavLink>

//获取
componentDidMount() {
   console.log(this.props.match.params.id);//2
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

King_960725

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值