You need to enable JavaScript to run this app. NextJS Amplify 首次页面刷新数据返回null 快速刷新后数据正常
优惠活动
大模型
产品
解决方案
定价
更多

NextJS Amplify 首次页面刷新数据返回null 快速刷新后数据正常

问题根因
  • 异步执行顺序错误:你在挂载触发的useEffect中并行调用了getStudentId和fetchActivations两个异步方法,fetchActivations执行时getStudentId还未完成鉴权查询,studentId仍是初始值null,导致GraphQL请求参数非法,返回异常数据进而抛出null相关错误。
  • 快速刷新正常的原因:NextJS的Fast Refresh机制会保留组件现有状态,修改代码触发热重载时,之前已经成功获取的studentId不会被重置,此时请求参数合法,数据就能正常加载。
  • 与是否使用getStaticProps无关:getStaticProps是构建阶段运行的服务端方法,无法获取客户端侧的用户登录状态,你这个需要依赖当前登录用户ID的场景本身就适合在客户端发起请求,不需要强行使用getStaticProps。
修复方案

调整异步逻辑依赖关系,等studentId成功获取后再触发列表查询,同时增加加载状态和异常兼容即可,修改后的参考代码如下:

const Activations = () => {
  const [activations, setActivations] = useState([]);
  const [studentId, setStudentId] = useState(null);
  const [loading, setLoading] = useState(true);

  // 页面挂载时仅获取当前登录用户ID
  useEffect(() => {
    getStudentId();
  }, []);

  // 监听studentId变化,存在有效值时再查询激活列表
  useEffect(() => {
    if (!studentId) return;
    fetchActivations();
  }, [studentId]);

  async function getStudentId() {
    try {
      const user = await Auth.currentAuthenticatedUser();
      setStudentId(user.attributes.sub);
    } catch (err) {
      console.log("error: getting user ", err);
      setLoading(false);
    }
  }

  async function fetchActivations() {
    try {
      setLoading(true);
      const activationData = await API.graphql({
        query: activationsByStudentId,
        variables: {
          studentId: studentId,
        },
      });
      // 增加可选链和默认值,避免接口返回异常时报错
      setActivations(activationData.data?.activationsByStudentId?.items || []);
    } catch (err) {
      console.log("error getting ativations", err);
    } finally {
      setLoading(false);
    }
  }

  // 加载过程中展示加载态,避免空状态异常渲染
  if (loading) return <div>加载中...</div>

  return (
    <>
      <h1 className="mb-5">Activations</h1>
      <div className="divide-y divide-gray-200">
        <Link href="/activations/create">
          <a>New Activation</a>
        </Link>
        {activations.map((activation, index) => (
          <Link key={index} href={`/activations/${activation.id}`}>
            <a className="flex py-2 ">{activation.title}</a>
          </Link>
        ))}
      </div>
    </>
  );
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 09:33:01