本页还没有译文
本页 14 段还没译成日本語,下面显示的是英文原文。createContext
还没翻译译自英文(reactrouter.com)本页 14 段都还没译
createContext
Framework Data
Summary
Creates a type-safe RouterContext object that can be used to
store and retrieve arbitrary values in actions,
loaders, and middleware.
Similar to React's createContext,
but specifically designed for React Router's request/response lifecycle.
If a defaultValue is provided, it will be returned from context.get()
when no value has been set for the context. Otherwise, reading this context
when no value has been set will throw an error.
app/context.ts
import { createContext } from "react-router";
// Create a context for user data
export const userContext =
createContext<User | null>(null);app/middleware/auth.ts
import { getUserFromSession } from "~/auth.server";
import { userContext } from "~/context";
export const authMiddleware = async ({
context,
request,
}) => {
const user = await getUserFromSession(request);
context.set(userContext, user);
};app/routes/profile.tsx
import { userContext } from "~/context";
export async function loader({
context,
}: Route.LoaderArgs) {
const user = context.get(userContext);
if (!user) {
throw new Response("Unauthorized", { status: 401 });
}
return { user };
}Signature
function createContext<T>(defaultValue?: T): RouterContext<T>Params
defaultValue
An optional default value for the context. This value will be returned if no value has been set for this context.
Returns
A RouterContext object that can be used with
context.get() and context.set() in actions,
loaders, and middleware.
AI 翻译查看英文原文