useState 钩子的 setState 函数的类型? [英] Type for the setState function of the useState hook?

查看:33
本文介绍了useState 钩子的 setState 函数的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将我的 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 parameter value and returns void.

  • 值:空 |博客 |((prevState: ...) => null | BLOGPOST)

    valuenullBLOGPOST 或接受参数 prevState 并返回 nullBLOGPOST.

  • value: null | BLOGPOST | ((prevState: ...) => null | BLOGPOST)

    value is either null, a BLOGPOST, or a function that accepts a parameter prevState and returns null or a BLOGPOST.

  • prevState: null |博文

    prevStatenullBLOGPOST.

这篇关于useState 钩子的 setState 函数的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆