Amm*_*med 3 typescript reactjs react-router-dom
我将加载器与 new 一起使用,当我在组件中react-router-dom使用钩子时,响应类型未知,因此我无法使用它。useLoaderData我不想使用as类型定义,因为我觉得这是一种作弊,但如果这是唯一的方法,那么,请告诉我:
我的加载器功能:
{
path: "/reset-password/:resetToken",
element: <ResetPassword />,
loader: async ({ params }) => {
if (!params.resetToken){
return null
}
const fakeTokens = ["abcdef123456", "bingbong", "foobar"]
// make API call to check if the given token is valid
const fakeAPICall = (resetToken: string) : Promise<object> => {
if (fakeTokens.includes(resetToken)){
return new Promise(resolve => resolve({ success: true }))
}
return new Promise(resolve => resolve({ success: false }))
}
const resp = await fakeAPICall(params.resetToken);
return resp;
}
},
Run Code Online (Sandbox Code Playgroud)
在 - 的里面<ResetPassword />:
// this type is "unknown", so I can't access the properties on it
const resetTokenResponse = useLoaderData()
Run Code Online (Sandbox Code Playgroud)
I personally preferred to wrap the original useLoaderData in another function (at least while it doesn't support generics):
export function useDataFromLoader<LoaderFn extends LoaderFunction>(loaderFn: LoaderFn) {
return useLoaderData() as Awaited<ReturnType<typeof loaderFn>>
}
Run Code Online (Sandbox Code Playgroud)
This new function takes the loader function you wrote to resolve its return type.
Then, instead of using the original useLoaderData, we can use the useDataFromLoader (or whatever you call it) and pass your loader fn to it (so it can figure out its return type):
async function loader() {
const data = await Promise.resolve({ foo: 'bar' })
return data
} satisfies LoaderFunction
function Component() {
const { foo } = useDataFromLoader(loader)
return <p>foo === 'bar': {foo === 'bar'}</p>
}
Run Code Online (Sandbox Code Playgroud)
And I also like to say that my loaders satisfies the original/expected LoaderFunction, so that we have access to params and request (for example) and to avoid any type mismatches when using it in the router.
| 归档时间: |
|
| 查看次数: |
1275 次 |
| 最近记录: |