interface AwaitProps<Resolve> {
    children: ReactNode | AwaitResolveRenderFunction<Resolve>;
    errorElement?: ReactNode;
    resolve: Resolve;
}

类型参数

  • Resolve

属性

children: ReactNode | AwaitResolveRenderFunction<Resolve>

当使用函数时,已解析的值将作为参数提供。

<Await resolve={reviewsPromise}>
{(resolvedReviews) => <Reviews items={resolvedReviews} />}
</Await>

当使用 React 元素时,useAsyncValue 将提供已解析的值

<Await resolve={reviewsPromise}>
<Reviews />
</Await>

function Reviews() {
const resolvedReviews = useAsyncValue()
return <div>...</div>
}
errorElement?: ReactNode

当 Promise rejected 时,错误元素会渲染,而不是 children。

<Await
errorElement={<div>Oops</div>}
resolve={reviewsPromise}
>
<Reviews />
</Await>

要提供更具上下文的错误,您可以在子组件中使用 useAsyncError

<Await
errorElement={<ReviewsError />}
resolve={reviewsPromise}
>
<Reviews />
</Await>

function ReviewsError() {
const error = useAsyncError()
return <div>Error loading reviews: {error.message}</div>
}

如果您不提供 errorElement,则 rejected 的值将冒泡到最近的路由级 ErrorBoundary,并通过 useRouteError hook 访问。

resolve: Resolve

接受从 loader 值返回的 Promise,以便解析和渲染。

import { useLoaderData, Await } from "react-router"

export async function loader() {
  let reviews = getReviews() // not awaited
  let book = await getBook()
  return {
    book,
    reviews, // this is a promise
  }
}

export default function Book() {
  const {
    book,
    reviews, // this is the same promise
  } = useLoaderData()

  return (
    

{book.title}

{book.description}

}>
); }