useState 钩子的 setState 函数的类型? [英] Type for the setState function of the useState hook?
问题描述
我正在将我的 React 项目转换为 Typescript.
I'm converting my React project to Typescript.
我有这个状态:
AdminBlogPostContainer.tsx
const [blogPost,setBlogPost] = useState<null | BLOGPOST>(null);
return(
<AdminBlogPostPage
blogPost={blogPost as BLOGPOST}
setBlogPost={setBlogPost}
/>
);
AdminBlogPostPage.tsx
interface AdminBlogPostPage {
blogPost: BLOGPOST,
setBlogPost: // <---- WHAT SHOULD I USE AS TYPE HERE ?
}
const AdminBlogPostPage: React.FC<AdminBlogPostPage> = (props) => {
console.log("Rendering AdminBlogPostPage...");
return(
// ...
);
};
export default AdminBlogPostPage;
这是错误信息:
推荐答案
让我们从 @types/react
.
declare namespace React {
// ...
type SetStateAction<S> = S | ((prevState: S) => S);
// ...
type Dispatch<A> = (value: A) => void;
// ...
function useState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>];
// ...
}
由此我们已经可以推断出语句中setBlogPost
的类型
From this we can already deduce the type of setBlogPost
in the statement
const [blogPost, setBlogPost] = useState<null | BLOGPOST>(null);
这是Dispatch
which is Dispatch<SetStateAction<null | BLOGPOST>>
, but let's break that down to see what each part means.
setBlogPost: (value: null | BLOGPOST | ((prevState: null | BLOGPOST) => null | BLOGPOST)) => void;
从外向内一次消化一件,我们得到以下解释:
Digesting that one piece at a time working from the outside in, we get the following explanation:
setBlogPost: (value: ...) =>无效
setBlogPost
是一个接受参数value
并返回void
的函数.
setBlogPost: (value: ...) => void
setBlogPost
is a function that accepts a parametervalue
and returnsvoid
.
值:空 |博客 |((prevState: ...) => null | BLOGPOST)
value
是null
、BLOGPOST
或接受参数prevState
并返回null
或BLOGPOST
.
value: null | BLOGPOST | ((prevState: ...) => null | BLOGPOST)
value
is eithernull
, aBLOGPOST
, or a function that accepts a parameterprevState
and returnsnull
or aBLOGPOST
.
prevState: null |博文
prevState
是null
或BLOGPOST
.
这篇关于useState 钩子的 setState 函数的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!