Remix 路由模块输出对象 handle

1,428 阅读1分钟

Remix handle 函数是一个有用的对外输出的 Route 模块对象,用于暴露特定的数据 match 对象,它们经常在一起使用。

当前 Remix 版本:1.15.0

在哪里可以定义 handle?

  • root 根组件
  • 路由页面

在根路由定义

import { /.../ } from "@remix-run/react";

// 根路由 handle 配合页面中 useMatches 获取到 app 数据
export const handle = {
  app: 1
}

export default function App() {
  return (
    <html lang="en">
      // ...
    </html>
  );

在页面 _index 路由中与 useMatch 一起

handle 与 useMatch 一起使用, useMatch 返回路由匹配相关的对象:

import type { V2_MetaFunction } from "@remix-run/node";

// hooks
import { useMatches } from "@remix-run/react";

export const meta: V2_MetaFunction = () => {
  return [{ title: "New Remix App" }];
};

// 输出定义 handle 对象
export const handle = {
  test: 1,
}

export default function Index() {
  const match = useMatches()
  console.log(match[1].test) // 在 match 中访问 match 函数
  return (
    <div>
      <h1>Welcome to Remix</h1>
    </div>
  );
}

match 数组

match 是一个数组, 数组中的对象数据结构:

  • data: 当前 loader 函数返回的数据
  • handle: 当前路由定义的 handle 数据
  • id:当前的路由 id
  • params: 当前的参数
  • pathname: 当前的路由路径

match 一般是一个数组,会有两个对象:

  • root.tsx 中的 match 对象
  • 当前路由的 match 对象

使用场景

当路由中需要指定一些特定的数据的时候

  • Remix-118i 中需要指定 handle
export const handle = { i18n: "login" };

i18n 提供给 Remix-i18n 用于根据当前路由匹配。

引用