待定 UI
本页内容

待定 UI

简介

当用户导航到新路由或向操作提交数据时,UI 应立即以待定或乐观状态响应用户的操作。应用程序代码负责此项工作。

全局待定导航

当用户导航到新 URL 时,会在下一页渲染之前等待下一页的加载器。您可以从 useNavigation 获取待定状态。

import { useNavigation } from "react-router";

export default function Root() {
  const navigation = useNavigation();
  const isNavigating = Boolean(navigation.location);

  return (
    <html>
      <body>
        {isNavigating && <GlobalSpinner />}
        <Outlet />
      </body>
    </html>
  );
}

局部待定导航

待定指示器也可以本地化到链接上。NavLink 的 children、className 和 style 属性可以是接收待定状态的函数。

import { NavLink } from "react-router";

function Navbar() {
  return (
    <nav>
      <NavLink to="/home">
        {({ isPending }) => (
          <span>Home {isPending && <Spinner />}</span>
        )}
      </NavLink>
      <NavLink
        to="/about"
        style={({ isPending }) => ({
          color: isPending ? "gray" : "black",
        })}
      >
        About
      </NavLink>
    </nav>
  );
}

待定表单提交

提交表单时,UI 应立即以待定状态响应用户的操作。使用 fetcher 表单最容易做到这一点,因为它有自己独立的状态(而普通表单会导致全局导航)。

import { useFetcher } from "react-router";

function NewProjectForm() {
  const fetcher = useFetcher();

  return (
    <fetcher.Form method="post">
      <input type="text" name="title" />
      <button type="submit">
        {fetcher.state !== "idle"
          ? "Submitting..."
          : "Submit"}
      </button>
    </fetcher.Form>
  );
}

对于非 fetcher 表单提交,待定状态可在 useNavigation 上获得。

import { useNavigation, Form } from "react-router";

function NewProjectForm() {
  const navigation = useNavigation();

  return (
    <Form method="post" action="/projects/new">
      <input type="text" name="title" />
      <button type="submit">
        {navigation.formAction === "/projects/new"
          ? "Submitting..."
          : "Submit"}
      </button>
    </Form>
  );
}

乐观 UI

当 UI 的未来状态由表单提交数据确定时,可以实现乐观 UI 以获得即时用户体验。

function Task({ task }) {
  const fetcher = useFetcher();

  let isComplete = task.status === "complete";
  if (fetcher.formData) {
    isComplete =
      fetcher.formData.get("status") === "complete";
  }

  return (
    <div>
      <div>{task.title}</div>
      <fetcher.Form method="post">
        <button
          name="status"
          value={isComplete ? "incomplete" : "complete"}
        >
          {isComplete ? "Mark Incomplete" : "Mark Complete"}
        </button>
      </fetcher.Form>
    </div>
  );
}

下一步:测试

文档和示例 CC 4.0
编辑