验证码: 看不清楚,换一张 查询 注册会员,免验证
  • {{ basic.site_slogan }}
  • 打开微信扫一扫,
    您还可以在这里找到我们哟

    关注我们

Remix路由模块输出对象loader函数怎么使用

阅读:808 来源:乙速云 作者:代码code

Remix路由模块输出对象loader函数怎么使用

      主要内容

      Remix loader 函数是一个获取当前页面页面数据的函数,经常与 useLoaderData 一起配合使用

      当前 Remix 版本:1.15.0

      • 定义方式

      • loader 与 useLoaderData 使用

      • 返回值类型以及使用方法

      • 参数/上下文

      • 重定向

      • 错误处理

      • laoder 操作纯 api 输出数据使用

      loader 函数定义

      • Remix Route 中定义 loader 函数

      • export 对外暴露

      • 返回 json/defer/ new Response 实例等

      经常与 ORM/ODM 进行交互,从数据库获取数据。

      loader 函数配合 useLoaderData 一起使用

      import { json } from "@remix-run/node"; // or cloudflare/deno
      export const loader = async () => {
        return json({ ok: true });
      };
      export default function Users() {
        const data = useLoaderData();
        return (
          <>{JSON.stringly(data)}
        );
      }

      loader 函数返回值

      • json 一般是同步数据,json 函数可以指定两个参数,第一个是 目标数据,第二个是 http 状态

      export const loader = () => {
        json({jsonKey: "jsonValue"})
      }
      export const loader = () => {
        json({jsonKey: "jsonValue"}, {
          status: 200,
          headers: {
            "Cache-Control": "no-store"
          }
        })
      }
      • defer 允许返回一个 promise, 一般配合 Await 组件使用

      json 数据一般是返回一个同步 json 对象,但是 defer 允许我们返回值可以是一个 promise

      import { defer } from "@remix-run/node"; // or cloudflare/deno
      export const loader = async () => {
        const thePromise = loadSlowDataAsync(); // 产生一个 Promise 值
        // So you can write this without awaiting the promise:
        return defer({
          critical: "data",
          slowPromise: thePromise, // 直接将 Promise 的值交给 defer
        });
      };

      值得注意的是 defer 返回的值不直接使用,需要配合 Suspense + Await 组件使用, 下面是一个 loader 返回 defer 的示例:

      import { defer } from "@remix-run/node";
      import { Await, useLoaderData } from "@remix-run/react";
      import { Suspense } from "react";
      export const loader = () => {
        let p = new Promise((resolve) => {
          setTimeout(() => {
            resolve("defer a promise value");
          }, 2000);
        });
        return defer({
          pv: p,
        });
      };
      export default function Defer() {
        const data = useLoaderData();
        console.log(data);
        return (
          
            
      This is defer value: 
            Loading...
      }>         {(data) => 
      {data}
      }            
      );
    export async function loader() {
      const body = JSON.stringify({ loader: "loader data"});
      return new Response(body, {
        headers: {
          "Content-Type": "application/json",
        },
      });
    }
    export default function() {
      return 
    loader.response
    }

    Response 是 Fetch API 的响应对象。

    loader 函数的类型

    loader 函数打通了其类型,在使用的是 typeof 执行 loader 函数配合 LoaderArgs 类型:

    import type { LoaderArgs } from "@remix-run/node";
    import { json } from "@remix-run/node";
    import { useLoaderData } from "@remix-run/react";
    export async function loader(args: LoaderArgs) {
      return json({ name: "Ryan", date: new Date() });
    }
    export default function SomeRoute() {
      const data = useLoaderData();
    }

    loader 函数中获取 params

    export async function loader({ params }: LoaderArgs) {
      let id = params.id; // "123"
    }

    一般 id 用于提供给后端查询数据库

    loader 函数中处理 headers

    export async function loader({ request }: LoaderArgs) {
      // read a cookie
      const cookie = request.headers.get("Cookie");
      // parse the search params for `?q=`
      const url = new URL(request.url);
      const query = url.searchParams.get("q");
    }

    从 request 对象使用 get 获取 “Cookie” headers 然后使用 request.url 获取 searchParams 这些常用的 url 数据。

    loader 函数上下文

    如果你有一些上下文,需要串可以修改 server.js 中的内容,这里以 exprss 为例:

    const {
      createRequestHandler,
    } = require("@remix-run/express");
    // 对所有的请求,创建一个对象,提供上下文
    app.all(
      "*",
      createRequestHandler({
        getLoadContext(req, res) {
          // this becomes the loader context
          return { expressUser: req.user };
        },
      })
    );
    // 在 loader 中使用上下文
    export async function loader({ context }: LoaderArgs) {
      const { expressUser } = context;
      // ...
    }

    loader 中重定向到

    import { redirect } from "@remix-run/node";
    export async function loader() {
      return redirect('/abc')
    }
    export default function() {
      return 
    loader.response
    }

    在 loader函数中能使用 redirect 函数进行重定向

    错误处理

    throw json(
          { invoiceOwnerEmail: invoice.owner.email },
          { status: 401 }
        );
    export function CatchBoundary() {
      // this returns { data, status, statusText }
      const caught = useCatch();
      switch (caught.status) {
        case 401:
          return (
            
              

    You don't have access to this invoice.

              

                Contact {caught.data.invoiceOwnerEmail} to get             access           

            
          );     case 404:       return 
    Invoice not found!
    ;   }   // You could also `throw new Error("Unknown status in catch boundary")`.   // This will be caught by the closest `ErrorBoundary`.   return (     
          Something went wrong: {caught.status}{" "}       {caught.statusText}     
      ); }

    在页面中的表现

    Remix路由模块输出对象loader函数怎么使用

    使用 loader 获取的数据,获取保存在 html 文档的 window.__remixContext 对象里面。

    loader 作为纯 api 输出数据使用

    Remix 是一个全栈框架,loader 函数用于对外输出数据,这里将 loader 定义为一个纯的 api 接口使用 loader 对外提供数据:

    export const loader = () => {
      return {
        a: 1
      }
    }

    启动服务,直接访问 /api/loader 接口得默认使用 get 方法 json 数据。如果要处理不同的请求方式,可以在 loader 函数的参数中获取。

    分享到:
    *特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: hlamps#outlook.com (#换成@)。
    相关文章
    {{ v.title }}
    {{ v.description||(cleanHtml(v.content)).substr(0,100)+'···' }}
    你可能感兴趣
    推荐阅读 更多>