一、什么是location
首先介绍的是location对象,location是BOM对象中最常用的一个对象之一,它提供了与当前窗口中加载的文档的有关的信息,还提供了一些导航的功能。说到这里,其实location是一个非常的特别的对象,因为window.location===document.location.另外location对解析URL非常的有帮助。
location一些常见属性:
- location.hostname - 返回 web 主机的域名
- location.pathname - 返回当前页面的路径和文件名
- location.port - 返回 web 主机的端口
- location.protocol - 返回所使用的 web 协议
- location.href - 返回当前页面URL
history一些常见的属性
-
history.length - 返回当前标签页历史记录长度
-
history.back() - 后退(相当于点击浏览器后退按钮)
-
history.forward() - 前进(相当于点击浏览器前进按钮)
-
history.go() - 前进或者后退(参数为负数后退,正数前进,0表示刷新当前页面)
react通过history.location.state来携带参数
一.state格式
history.push(path, [state])
<Redirect to={{pathname: '/xxx', state: {} }}
二.实际操作
1.用history.push方法携带state参数
history.push('/login', { from: history.location.pathname })
2.用Redirect里的to属性携带state参数
<Redirect to={{pathname: '/login',state: { from: history.location.pathname }}}/>
3.在login页面查看传过来的state参数
import { useHistory } from 'react-router'
const Login = () => {
const history = useHistory()
console.log(history, 'history')
}
4.跳转回原页面
history.replace(history.location.state.from || '/home')
项目里面,不让用push : 重定向到登录,别用push,push会有记录。所以查了一下,用replace代替push。
用history.push,和history.go或者replace其他方式去改变当前的location有什么特别的区别:
history.push 这个方法会向history栈里面添加一条新记录,这个时候用户点击浏览器的回退按钮可以回到之前的路径。
history.go 这个方法的参数是一个整数,意思是在 history 记录中向前或者后退多少步,类似 window.history.go(n)
history.replace 跟 history.push 很像,唯一的不同就是,它不会向 history 添加新记录,而是跟它的方法名一样 —— 替换掉当前的 history 记录。
history.push和history.replace场景:
点击登录,进入页面,再随便点击一个页面。如果是push,点击回退,会回到登录页。但是replace,就回到上次点击的页面,不会回到登录页。(测试的时候重新开一个页面)