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

React.js页面仅显示Loading...但URL含完整姓名的问题排查

Next.js 表单提交后展示页一直显示Loading的问题修复

问题原因

你的展示页代码存在关键错误:在Next.js App Router的useRouter中,router.query本身就是解析完成的URL查询参数对象,不需要再用new URLSearchParams(router.query)处理。这种错误用法会导致无法正确获取first_name和last_name参数,进而first_name && last_name条件不成立,loading状态始终无法设为false,页面一直卡在Loading状态。

另外,useEffect的依赖数组里不需要添加router,因为useRouter返回的是稳定引用,重复添加会触发不必要的重渲染。

修复方案

方案一:直接从router.query提取参数(推荐)

修改展示页的useEffect逻辑,直接从router.query中读取参数:

'use client';
import React, { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';

export default function Display() {
  const [fullName, setFullName] = useState('');
  const [loading, setLoading] = useState(true);
  const router = useRouter();

  useEffect(() => {
    if (router.isReady) {
      // 直接从router.query中获取参数
      const first_name = router.query.first_name;
      const last_name = router.query.last_name;

      if (first_name && last_name) {
        setFullName(`${first_name} ${last_name}`);
        setLoading(false);
      } else {
        router.replace('/form');
      }
    }
  }, [router.isReady, router.query]); // 移除不必要的router依赖

  if (loading) {
    return <p>Loading...</p>;
  }

  return (
    <div>
      <nav>
        <Link href='/form' passHref>
          Go Back
        </Link>
      </nav>
      <h1>Full Name: {fullName}</h1>
    </div>
  );
}

方案二:基于window.location.search使用URLSearchParams

如果你更习惯URLSearchParams API,可以用当前页面的window.location.search来创建实例:

'use client';
import React, { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';

export default function Display() {
  const [fullName, setFullName] = useState('');
  const [loading, setLoading] = useState(true);
  const router = useRouter();

  useEffect(() => {
    if (router.isReady) {
      // 基于当前页面的URL查询字符串创建实例
      const searchParams = new URLSearchParams(window.location.search);

      const first_name = searchParams.get('first_name');
      const last_name = searchParams.get('last_name');

      if (first_name && last_name) {
        setFullName(`${first_name} ${last_name}`);
        setLoading(false);
      } else {
        router.replace('/form');
      }
    }
  }, [router.isReady]); // 无需依赖router.query,window.location.search会实时同步URL变化

  if (loading) {
    return <p>Loading...</p>;
  }

  return (
    <div>
      <nav>
        <Link href='/form' passHref>
          Go Back
        </Link>
      </nav>
      <h1>Full Name: {fullName}</h1>
    </div>
  );
}

额外说明

表单页的代码逻辑没有问题,参数已经正确通过URL传递,只需修复展示页的参数获取逻辑即可解决问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 21:30:27