React
例如: 同一个路由/testLSX,但是参数不同
- /testLSX
- /testLSX?name=12_age=12
- /testLSX?name=13_age=12
函数式组件
import React, { useEffect, useState } from "react";
export default ({
history,
}) => {
const [href] = useState(window.location.href);
useEffect(() => {
console.log("hello lushuixi", window.location.href); // /testLSX?name=12_age=12
const timer = new Date().getTime();
console.log("初态", timer);
handleInit(timer);
}, []);
useEffect(() => {
console.log("href", href);
}, [href]);
const handleInit = (timer) => {
setTimeout(() => {
console.log("2000ms之后");
callback(timer);
}, 2500);
}
const callback = timer => {
console.log("callback:", new Date().getTime() - timer, href);
history.push("/testLSX?name=13_age=12")
}
return (
<div>
<span>测试{href}</span>
</div>
)
}
打印结果:
hello lushuixi http://localhost:3000/testLSX?name=12_age=12
vconsole.min.js:10 初态 1639927614696
vconsole.min.js:10 href http://localhost:3000/testLSX?name=12_age=12
vconsole.min.js:10 2000ms之后
vconsole.min.js:10 callback: 2504 http://localhost:3000/testLSX?name=12_age=12
发现在同一页面下,【路由跳转到同一路由,但参数不同】,该页面并没有重新加载
加上history.listen(route => {...}),便可以了
类组件
import React from "react";
class TestLSX extends React.Component {
state = {
href: window.location.href,
};
componentDidMount() {
const timer = new Date().getTime();
console.log("初态", timer);
this.handleInit(timer);
this.props.history.listen(route => {
console.log("监听路由变化", route)
this.handleInit(timer)
})
}
// componentWillUpdate() {
// console.log("更新", this.state.href);
// const timer = new Date().getTime();
// console.log("初态", timer);
// this.handleInit(timer);
// }
handleInit(timer) {
setTimeout(() => {
this.callback(timer)
}, 2000);
}
callback(timer) {
console.log("callback:", new Date().getTime() - timer, );
if(window.location.href === window.location.origin + "/testLSX?name=13_age=12") return;
this.props.history.push("/testLSX?name=13_age=12");
}
render() {
const { href, } = this.state;
return (
<div>测试{href}</div>
)
}
}
export default TestLSX
监听到了同一路由参数的变化 this.props.history.listen(route => {...)