React分页切换时无法获取当前URL的技术求助
问题解决方法
问题根源
- URL获取不完整:你使用
location.pathname仅能获取URL的路径部分(如/my-lists.html),不包含查询参数(?page=xxx),所以分页切换时查询参数变化不会体现在打印结果中。 - useEffect依赖缺失:你的
useEffect仅监听currentPage变化,但URL查询参数更新时location对象会发生变化,却未被加入依赖数组,导致useEffect不会重新执行获取最新URL。
修正后的代码
import { PageLoad} from './PageLoad' import { useLocation, useEffect } from "react-router-dom"; const Pagination = (props) => { const location = useLocation(); const { currentPage, setPage, totalPages } = props.pageControl; useEffect(() => { // 获取完整URL(包含查询参数) const fullURL = location.href; // 或手动拼接路径与查询参数:const fullURL = `${location.pathname}${location.search}`; PageLoad(fullURL); }, [location, currentPage]); // 加入location作为依赖,确保URL变化时触发 } // PageLoad函数保持不变 const PageLoad= (URL) => { console.log(URL); }
关键说明
- 用
location.href可以直接拿到包含查询参数的完整URL,也可以通过location.pathname + location.search手动拼接,两种方式都能获取到带page参数的完整地址。 - 将
location加入useEffect的依赖数组后,只要URL的任何部分(包括查询参数)发生变化,useEffect就会重新执行,从而打印出最新的URL。
内容的提问来源于stack exchange,提问作者Kiran Kumar V
相关产品推荐
相关产品推荐

