用于创建复杂的、动态的用户界面,这些界面需要多个并发数据交互而不会导致导航。
Fetchers 跟踪自己独立的状态,可用于加载数据、提交表单,以及通常与 action
和 loader
函数进行交互。
import { useFetcher } from "react-router"
function SomeComponent() {
let fetcher = useFetcher()
// states are available on the fetcher
fetcher.state // "idle" | "loading" | "submitting"
fetcher.data // the data returned from the action or loader
// render a form
<fetcher.Form method="post" />
// load data
fetcher.load("/some/route")
// submit data
fetcher.submit(someFormRef, { method: "post" })
fetcher.submit(someData, {
method: "post",
encType: "application/json"
})
}
function useFetcher<T = any>({
key,
}: {
key?: string;
} = ): FetcherWithComponents<SerializeFrom<T>> {}
用于标识 fetcher 的唯一键。
默认情况下,useFetcher
会生成一个作用于该组件的唯一 fetcher。如果你想用自己的键来标识一个 fetcher,以便在应用程序的其他地方访问它,你可以使用 key
选项来实现。
function SomeComp() {
let fetcher = useFetcher({ key: "my-key" })
// ...
}
// Somewhere else
function AnotherComp() {
// this will be the same fetcher, sharing the state across the app
let fetcher = useFetcher({ key: "my-key" });
// ...
}
一个 FetcherWithComponents
对象,其中包含 fetcher 的状态、数据以及用于提交表单和加载数据的组件。