简体   繁体   English

更新打字稿版本时反应 useState 钩子上的打字稿错误

[英]Typescript error on react useState hook when updating typescript version

I developed a react typescript application with react 16.9 and typescript 3.5.2.我使用 react 16.9 和 typescript 3.5.2 开发了一个 react typescript 应用程序。 It uses react state hooks like它使用像这样的反应状态钩子

const [hValue, setHValue] = useState();

type of the hValue is IValue hValue类型是IValue

So the setHValue has return type React.Dispatch<any>所以setHValue有返回类型React.Dispatch<any>

Then I updated the typescript version to 3.9.7 and it gives compilation errors and it seems that now the return type of setHValue has changed to React.Dispatch<React.SetStateAction<undefined>>然后我将打字稿版本更新为 3.9.7,它给出了编译错误,现在似乎setHValue的返回类型已更改为React.Dispatch<React.SetStateAction<undefined>>

Why is that?这是为什么? and how to resolve this issue?以及如何解决这个问题?

Let's have a look at the type of useState我们来看看useState的类型

    function useState<S = undefined>(): [S | undefined, Dispatch<SetStateAction<S | undefined>>];

It is to say, if you didn't specify any S , it will be undefined by default.也就是说,如果没有指定任何S ,则默认为undefined

So you will need to specify your initial type, say if hValue is a number , you can do所以你需要指定你的初始类型,比如如果hValue是一个number ,你可以做

const [hValue, setHValue] = useState<number>();

In this way, setValue will be React.Dispatch<SetStateAction<number>> type这样setValue就会是React.Dispatch<SetStateAction<number>>类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM