日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

React路由攔截模式及withRouter示例詳解_React

作者:你華還是你華 ? 更新時間: 2022-09-29 編程語言

一、路由攔截

在前面兩篇 路由博客基礎上,我們將ReactRouter.js的我的profile路由設置成路由攔截的:

<Route path="/profile" render={() => 
                isAuth() ? <Profile/> : <Redirect to="/login"></Redirect>
              }></Route>

新建Login.js組件,寫入代碼:

import React, { Component } from 'react'

export default class Login extends Component {
  render() {
    return (
      <div>
          <h2>Login</h2>
          <input type="text"></input>
          <button onClick={() => {
              localStorage.setItem('token', 123  )
              this.props.history.push('/profile')
          }}>模擬登錄</button>
      </div>
    )
  }
}

效果:

二、路由模式

之前帶#號的路由模式為哈西模式,如果想不帶#號的話,可以寫成如下:

但是BrowserRouter沒有#路徑,后端如果沒有對應的路徑處理邏輯,就會404。

三、withRouter

如果我們在我的頁面里面還有我的訂單路由的話,那么在Profile.js中寫入跳轉的語法:

import React from 'react'

export default function Profile(props) {
  return (
    <div>
        <h1>Profile</h1>
        <div onClick={() => {
          props.history.push('/profileorder')
        }}>我的訂單</div>
      </div>
  )
}

可以看到報錯了,那我們之前那種寫法不生效了嗎。其實跟路由的創建有關系,之前是直接將組件用component屬性直接傳了過去,所以propshistory對象,但是這次我們是采用的render將組件在立即函數中實例化了,不傳進去:

所以在這里props接收不到任何東西,是非常正常的。在使用render的路由時,我們可以這樣傳參:

通過傳props那么子組件中將有路由的一些屬性,就可以做跳轉。如果在路由組件上不傳props的話,那么將使用withRouter進行跳轉。將props刪除:

可以看到即使render的路由父組件不傳props,我們使用withRouter,也能夠進行路由的跳轉。

原文鏈接:https://blog.csdn.net/weixin_44103733/article/details/123555893

欄目分類
最近更新