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

Remix提取资源路由实现多端数据复用,UI路由数据获取方法咨询

Remix 架构重构:共享JSON资源路由与UI路由数据复用

第一步:迁移逻辑到资源路由

首先创建app/routes/place/$id[.json].ts资源路由,把原UI路由的loader逻辑完整迁移过去:

// app/routes/place/$id[.json].ts
import { json, LoaderArgs } from "@remix-run/node";
import invariant from "tiny-invariant";
import { getPlace } from "~/lib/places"; // 后续建议抽离到共享文件

export async function loader({ params }: LoaderArgs) {
  invariant(params.id, "id not found");

  const place = await getPlace({ id: params.id });
  if (!place) {
    throw new Response("Not Found", { status: 404 });
  }
  return json({ place });
}

原UI路由获取数据的两种方式

方式1:直接调用共享业务逻辑(推荐)

最高效的方式是把getPlace这类核心业务逻辑抽离到独立的共享文件(比如~/lib/places.ts),原UI路由的loader直接调用该函数,无需走HTTP请求:

// app/routes/place/$id.tsx
import { json, LoaderArgs } from "@remix-run/node";
import invariant from "tiny-invariant";
import { getPlace } from "~/lib/places";

export async function loader({ params }: LoaderArgs) {
  invariant(params.id, "id not found");

  const place = await getPlace({ id: params.id });
  if (!place) {
    throw new Response("Not Found", { status: 404 });
  }
  return json({ place });
}

// 原UI组件部分保持不变
export default function PlacePage() {
  const { place } = useLoaderData<typeof loader>();
  // ... 渲染UI逻辑
}

这种方式避免了内部HTTP请求开销,代码复用性最高,同时资源路由仍能为React Native端提供JSON接口。

方式2:使用fetch调用资源路由(仅适合特定场景)

如果需要模拟外部请求的测试场景,可以在UI路由的loader中调用资源路由URL,但要注意构建完整请求路径:

// app/routes/place/$id.tsx
import { json, LoaderArgs } from "@remix-run/node";
import invariant from "tiny-invariant";

export async function loader({ params, request }: LoaderArgs) {
  invariant(params.id, "id not found");

  // 基于当前请求构建资源路由的完整URL
  const url = new URL(`/place/${params.id}.json`, new URL(request.url).origin);
  const response = await fetch(url);
  
  if (!response.ok) {
    throw new Response("Not Found", { status: 404 });
  }

  const data = await response.json();
  return json(data);
}

该方式会增加额外HTTP请求开销,日常开发优先选择方式1。

架构优化建议

  • 抽离共享逻辑层:将getPlace、数据验证、错误处理等核心逻辑放到~/lib目录的独立文件中,让资源路由、UI路由甚至React Native端都能直接调用(React Native可通过npm包共享或复制代码)。
  • 统一资源路由规范:所有跨端复用的JSON接口都用[.json].ts后缀的资源路由管理,保持接口路径一致,方便移动端统一维护API请求。
  • 复用错误处理逻辑:将404、权限验证等通用错误处理抽离成工具函数,避免在多个路由中重复编写相同的错误抛出逻辑。
  • 类型共享:把Place相关的TypeScript类型定义放到共享文件中,Web端和React Native端复用同一套类型,保证类型一致性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 14:22:29