返回
React路径不变location.search参数改变不触发useEffect
2022-11-13 3628 0
React项目里有两个菜单项会到同一个pathname但是参数不同,这两个页面切换时不会触发页面数据刷新(切换url页面代码不会重新执行)。原来的做法是用window.location.search获取参数,在别的地方都没有问题,这里比较特殊,因为是相同路径的页面跳转。
const currDirection = new URLSearchParams(window.location.search).get("direction");
console.log(currDirection);
useEffect(()=>{
// to do
},[window.location.search或者direction]);即使把window.location.search放在useEffect数组里,在从path?direction=1切换到path?direction=2时页面不会刷新。切换时根本执行到获取参数打印log。
解决办法是
import { useLocation } from "react-router-dom";
const location = useLocation();
const currDirection = new URLSearchParams(location.search).get("direction");
console.log(currDirection);
useEffect(()=>{
// to do
},[direction])这样url参数变化时会触发useEffect,也就是参数变化时会执行获取参数的代码,并且触发useEffect。
虽然两个location对象用法类似,但是测试下来,只要调用过useLocation(),那么url变化时页面代码会重新执行,否则不会执行没有任何log。所以像下面这样也没有问题,只跟是否调用useLocation()有关。
const location = useLocation(); // 只声明,并未使用
const currDirection = new URLSearchParams(window.location.search).get(
"direction"
);
console.log(currDirection);
useEffect(()=>{
// to do
},[window.location.search,currDirection或者direction]); // 页面代码重新执行并且触发useEffect
网友点评
提交
相关阅读
如何在React使用TypeScript?
Hugeicons 提供4000+免费React图标库
如何在 React 中使用 GraphQL
如何在React中使用Redux?
React Error: Exceeded timeout of 5000 ms for a test. 错误
国外流行的前端框架有哪些?
Vue和React怎么选?
React和Next.js的关系?
相关帖子
DOVE加速器套餐价格对比:标准、高级、尊贵与企业版哪个最值得购买?
六尺巷VP机场怎么样?六尺巷VP官网打不开,不能用了?六尺巷VP机场跑路了?推荐替代 – DOVE加速器
在路由器中配置加速器的最佳推荐与设置指南
免费好用的外网加速器排行榜:2025 年最佳科学上外网工具
MoneyPrinterTurbo是什么?一键生成AI短视频的开源神器详解
ChatGPT is at capacity right now ChatGPT负载太高挂掉了~
魔兽怀旧服plus猎人-远程玩法天赋符文
aca & misakaf emby官方机场不能用了?aca & misakaf emby官方机场跑路了?推荐替代 – DOVE加速器