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

如何在Remix的LoaderFunction中返回多组数据集渲染多个下拉选框?

如何在Remix的LoaderFunction中返回多组数据集?

我似乎误解了LoaderFunction的工作机制。我的路由中有一个包含两个下拉选择框的简单表单,每个选择框的数据分别来自不同的数据库表。最初我只实现了一个选择框,代码如下:

export const loader: LoaderFunction = async ({ params, request }: LoaderFunctionArgs) => {
    return await getItemTypes("1"); // <-- 来自Prisma
};
...
const itemTypes = useLoaderData<typeof loader>();
...
<select name="itemType">
{itemTypes.map((itemType) =>
  <option key={itemType.itemTypeId} value={itemType.itemTypeId}>
    {itemType.itemTypeName}
  </option>
)}
</select>

这部分运行正常,但现在我需要添加第二个对应itemCategory的下拉选择框。我了解到LoaderFunction似乎只能返回单个响应,请问该如何实现返回多组数据集?


解决方案

LoaderFunction确实只能返回单个响应,但你可以把多组数据打包成一个对象返回,这样就能在组件中同时获取多组数据集了。具体实现如下:

  1. 修改Loader函数,返回包含多组数据的对象
    推荐用Promise.all并行获取两个数据集,提升查询效率,再把结果封装到对象中返回:
export const loader: LoaderFunction = async ({ params, request }: LoaderFunctionArgs) => {
  // 并行执行两个数据库查询
  const [itemTypes, itemCategories] = await Promise.all([
    getItemTypes("1"),
    getItemCategories("1") // 替换为你获取分类数据的Prisma方法
  ]);

  // 返回包含两组数据的对象
  return { itemTypes, itemCategories };
};
  1. 在组件中解构获取多组数据
    使用useLoaderData时,直接解构返回的对象即可拿到两类数据:
const { itemTypes, itemCategories } = useLoaderData<typeof loader>();
  1. 渲染第二个下拉选择框
    用相同逻辑渲染itemCategory的下拉框:
<select name="itemCategory">
{itemCategories.map((category) =>
  <option key={category.categoryId} value={category.categoryId}>
    {category.categoryName}
  </option>
)}
</select>

关键提示

  • Remix会自动序列化Loader返回的响应,只要你的数据是可序列化类型(比如Prisma返回的模型对象),就能正常传递到组件。
  • 用Promise.all并行执行查询,比串行调用更节省时间。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 04:00:06