You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React分页切换时无法获取当前URL的技术求助

问题解决方法

问题根源

  1. URL获取不完整:你使用location.pathname仅能获取URL的路径部分(如/my-lists.html),不包含查询参数(?page=xxx),所以分页切换时查询参数变化不会体现在打印结果中。
  2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 02:55:20