yuadhのinterview_note yuadhのinterview_note
前端基础
软件框架
算法|数据结构
基础学科
系统|工具
项目
面试综合
专栏
GitHub (opens new window)
前端基础
软件框架
算法|数据结构
基础学科
系统|工具
项目
面试综合
专栏
GitHub (opens new window)
  • vscode

  • vue

  • react

    • heima

      • react快速开始
      • react受控和非受控组件
      • react组件通信
      • react生命周期
      • react路由
      • react的hooks
      • react生态redux
      • react生态router
        • Router
        • 编程式导航
    • react官方

  • 软件框架
  • react
  • heima
yuadh
2022-12-06
目录

react生态router

# Router

yarn add react-router-dom@5

import {BrowserRouter as Router,Route,Link} from 'react-router-dom'
1

# 编程式导航

目标:能够按钮的点击事件中跳转路由

内容:

  • 场景:点击登录按钮,登录成功后,通过代码跳转到后台首页,如何实现?
  • 编程式导航:通过 JS 代码来实现页面跳转
  • 可以通过 useHistory hook 来拿到路由提供的 history 对象,用于获取浏览器历史记录的相关信息。常用操作:
    • push(path):跳转到某个页面,参数 path 表示要跳转的路径
    • replace(patch):跳转到某个页面,会替换当前的历史记录
    • go(n): 前进或后退到某个页面,参数 n 表示前进或后退页面数量(比如:-1 表示后退到上一页)
import { useHistory } from 'react-router-dom'

const Login = () => {
  const history = useHistory()
  
	const onLogin = () => {
    // ...
    history.push('/home')
  }
  return (
  	<button onClick={onLogin}>登录</button>
  )
}
1
2
3
4
5
6
7
8
9
10
11
12
13

push(path)和 replace(path) 跳转路由的区别:

浏览器会自动记录访问过来的页面路径,可以简单的把理解为通过一个 数组 来记录的。

比如:我们访问了 3 个页面:['/login', '/home', '/search'],当前所在页面为:'/search'

  1. 此时,如果我们又通过 push('/a') 方法访问了一个新页面:'/a',此时,就相当于往数组中 push 了一条数据,

    • 那么,访问该页面后,浏览器中的记录为:['/login', '/home', '/search', '/a']
  2. 此时,如果我们又通过 replace('/a') 方法访问了一个新页面:'/a',此时,就相当于把当前页面地址,替换为 '/a'

    • 那么,访问该页面后,浏览器中的记录为:['/login', '/home', '/a']
编辑 (opens new window)
上次更新: 2023/02/07, 15:11:55
react生态redux
核心概念

← react生态redux 核心概念→

最近更新
01
青训营真题day01
02-07
02
01day01-html与css
02-07
03
day02-js
02-07
更多文章>
Theme by Vdoing | Copyright © 2022-2023 yuadh | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式