如何为React挂钩(useState等)进行流类型注释?

tim*_*hym 10 reactjs flowtype

我们应该如何在带有React钩子的Flow类型注释中使用useState?我尝试搜索一些应如何实施的示例,但找不到任何内容。

我尝试了这个:

const [allResultsVisible, setAllResultsVisible]: [ boolean, (boolean) => void, ] = useState(false);
Run Code Online (Sandbox Code Playgroud)

不会引发任何与流相关的错误,但是我不确定这是否正确,还是注释该钩子的最佳方法。如果我的尝试不正确或最佳方法,我应该怎么做?

And*_*paw 9

Flow会推断类型,如PR所示,它为Flow库增加了对钩子的支持。

更新

正如我在对另一个答案的评论中所讨论的那样,必须在上下文中使用结果变量才能使类型检查按预期工作。

const [loading, setLoading] = React.useState(true);
(loading: boolean);

setLoading('foo') // Flow error
Run Code Online (Sandbox Code Playgroud)

const [loading, setLoading] = React.useState(true);

setLoading('foo') // no Flow error
Run Code Online (Sandbox Code Playgroud)

  • 您还可以使用类型参数`const [loading,setLoading] = useState <boolean>(true);` (10认同)