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

useNavigate与useParams配合异常及页面刷新空白问题

React Router 导航与页面刷新问题排查与解决

问题描述

1. CreateBlog页面指定路由导航无效

从/createblog?ProjectId=xxxxxx页面点击取消按钮时,使用navigate(-1)可正常返回上一页,但使用navigate(/content/${projectId})无法跳转至目标路由。控制台能输出正确的projectId值,且该路由从/content页面跳转时可正常工作。

2. 带查询参数的ProjectPage刷新后空白

访问localhost:3000/content/projectId?pageId=xxxxxx时页面可正常展示博客内容,但刷新该URL后页面完全空白;而刷新localhost:3000/content/projectId页面时一切正常。


解决方案

问题1:修复CreateBlog页面导航逻辑

由于进入CreateBlog页面的URL携带的是查询参数ProjectId,而非路由参数,需使用useSearchParams钩子获取该值,而非useParams。

修改CreateBlog页面代码:

import { useNavigate, useSearchParams } from 'react-router-dom';

const CreateBlog = () => {
  const [searchParams] = useSearchParams();
  const projectId = searchParams.get('ProjectId'); // 匹配URL中的查询参数名
  const navigate = useNavigate();

  const handleClick = () => {
    // 确保projectId存在再执行导航
    if (projectId) {
      navigate(`/content/${projectId}`);
    }
  };

  // ...其他组件代码
};

额外检查点:

  • 确认路由配置中/content/:projectId的路径定义正确(App.js中配置无误)
  • 若仍存在问题,可尝试使用对象形式的导航参数:
    navigate({ pathname: `/content/${projectId}` });
    

问题2:修复ProjectPage刷新后数据丢失问题

页面刷新空白的核心原因是:location.state存储在内存中,刷新后会丢失,而原代码依赖location.state匹配项目数据,导致pagesname无法被正确设置。

修改ProjectPage页面逻辑,改用路由参数projectId匹配项目数据:

import React, { useEffect, useState } from "react";
import { useParams, useSearchParams } from "react-router-dom";
import axios from "axios";

const ProjectPage = () => {
  const { projectId } = useParams();
  const [pagesname, setPagesname] = useState([]);
  const [dashboarderror, setDashboarderror] = useState();
  const [searchParams] = useSearchParams();
  const pageId = searchParams.get("pageId");

  useEffect(() => {
    async function fetchData() {
      try {
        const authconfig = {
          headers: {
            "Content-Type": "application/json",
            Authorization:
              "Bearer " + JSON.parse(localStorage.getItem("user_token")).token,
          },
        };
        const res = await axios.get(dashboardURL, authconfig);
        // 用projectId匹配目标项目,替代原有的location.state判断
        const targetProject = res.data.matrixDetails[2].projects.find(
          project => project.projectKeyId === projectId
        );
        if (targetProject) {
          setPagesname(targetProject.pages);
        }
      } catch (e) {
        setDashboarderror(e);
      }
    }
    fetchData();
  }, [projectId]); // 依赖项改为projectId,确保路由参数变化时重新请求数据

  return (
    <Box>
      {pagesname.map((sname) => (
        <div key={sname.pageKeyId}>
          <Button
            style={{
              textTransform: "none",
              color: "#546e7a",
              backgroundColor: "transparent",
              padding: "2px",
            }}
            onClick={() => searchParams.set("pageId", sname.pageKeyId)}
          >
            <DataTreeView
              treeItems={pagesname}
              pgCode={sname.pageKeyId}
            />
          </Button>
        </div>
      ))}
      {pageId && <PageView pageId={pageId} />}
    </Box>
  );
};

同时修复原代码中的语法错误:移除setPagesname行后多余的闭合括号。


内容的提问来源于stack exchange,提问作者Udayendu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 01:37:17