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

如何在Remix.run中正确使用useFetcher()的load()方法?遇404及data未定义问题

问题分析与修复方案

核心问题

你的代码存在三个关键问题,导致出现404错误且fetcher.data始终为undefined:

  1. API路由的文件命名不符合Remix规范
  2. Loader函数未正确返回JSON格式的响应
  3. useEffect的定时器清理逻辑错误,且请求使用了硬编码的绝对路径

修复步骤

1. 调整API路由的文件结构与名称

Remix的API路由需要放在app/routes/api/目录下,文件名改为time.jsx(而非api.time.jsx),这样路由路径/api/time才能被框架正确识别。

2. 修正Loader函数的返回格式

Remix的loader必须返回Response类型对象,需要使用json()助手来序列化数据:

// app/routes/api/time.jsx
import { json } from "@remix-run/node";

export const loader = () => {
  return json({ time: new Date().toLocaleString() });
};

3. 修复useEffect逻辑与请求路径

  • 把绝对路径改为相对路径/api/time,适配不同运行环境
  • 调整定时器的清理逻辑,确保组件卸载时能正确清除定时器
  • 优化依赖项,避免不必要的重渲染操作

修正后的time.jsx代码:

// time.jsx
import { useEffect, useRef } from "react";
import { useFetcher } from "@remix-run/react";

export default function Time() {
  const fetcher = useFetcher();
  const intervalRef = useRef(null);

  useEffect(() => {
    intervalRef.current = setInterval(() => {
      if (fetcher.state === "idle") {
        fetcher.load("/api/time");
      }
    }, 1000);

    return () => clearInterval(intervalRef.current);
  }, [fetcher.state]);

  return (
    <div>
      <h2>Time</h2>
      <p>{fetcher.data?.time || "Loading..."}</p>
    </div>
  );
}

额外说明

  • 使用fetcher.data?.time可选链操作符,避免数据未加载时出现报错
  • 用useRef保存定时器实例,确保清理时能正确获取到定时器ID
  • 将依赖项改为fetcher.state,减少useEffect的触发次数,优化性能

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 18:22:11