網站首頁 編程語言 正文
一、路由攔截
在前面兩篇 路由博客基礎上,我們將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
屬性直接傳了過去,所以props
有history
對象,但是這次我們是采用的render
將組件在立即函數中實例化了,不傳進去:
所以在這里props
接收不到任何東西,是非常正常的。在使用render
的路由時,我們可以這樣傳參:
通過傳props
那么子組件中將有路由的一些屬性,就可以做跳轉。如果在路由組件上不傳props
的話,那么將使用withRouter
進行跳轉。將props
刪除:
可以看到即使render
的路由父組件不傳props
,我們使用withRouter
,也能夠進行路由的跳轉。
原文鏈接:https://blog.csdn.net/weixin_44103733/article/details/123555893
相關推薦
- 2023-05-30 python元類編程的基本使用_python
- 2022-01-05 npm install 報錯:npm ERR! code EPERM npm ERR! syscal
- 2022-06-11 嵌入式C語言二級指針在鏈表中的應用_C 語言
- 2022-04-17 mac 使用zsh vscode和終端node默認版本不一致 (nvm node版本管理工具)
- 2023-03-01 MATLAB?plot函數功能及用法詳解_其它綜合
- 2022-02-13 pip install dlib報C++11 is required to use dlib
- 2022-06-11 docker安裝elastic?search和kibana的實現_docker
- 2022-08-15 form表單驗證錯誤提示語太長無法全部展示的問題
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支