Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何为React钩子(useState等)进行流类型注释?_Reactjs_Flowtype - Fatal编程技术网

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

Reactjs 如何为React钩子(useState等)进行流类型注释?,reactjs,flowtype,Reactjs,Flowtype,我们应该如何将流类型注释与react挂钩一起使用,例如useState?我试着搜索一些应该如何实现它们的示例,但找不到任何东西 我试过这个: const[allResultsVisible,setAllResultsVisible]:[boolean,(boolean)=>void,]=useState(false); 这不会抛出任何与流相关的错误,但我不确定这是正确的还是注释钩子的最佳方法。如果我的尝试不正确或不是最好的方法,我应该怎么做呢?Flow推断类型,因为这增加了对流库挂钩的支持 更

我们应该如何将流类型注释与react挂钩一起使用,例如
useState
?我试着搜索一些应该如何实现它们的示例,但找不到任何东西

我试过这个:

const[allResultsVisible,setAllResultsVisible]:[boolean,(boolean)=>void,]=useState(false);
这不会抛出任何与流相关的错误,但我不确定这是正确的还是注释钩子的最佳方法。如果我的尝试不正确或不是最好的方法,我应该怎么做呢?

Flow推断类型,因为这增加了对流库挂钩的支持

更新

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

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

setLoading('foo') // Flow error
vs


类型推断对我不起作用:

const [loading, setLoading] = React.useState(true) // boolean
setLoading('foo') // no Flow error
setLoading(1) // no Flow error
必须手动添加打字:

const [loading, setLoading]: [boolean, ((boolean => boolean) | boolean) => void] = React.useState(false)
setLoading('foo') // Flow error
setLoading(1) // Flow error
我有:

"react": "16.8.6",
"flow-bin": "0.100.0",
更新 正如@AndrewSouthpaw所指出的,
加载
必须在某些上下文中使用,否则
设置加载
将无法正常工作

这项工作:

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

setLoading('foo'); // Flow error
不带分号的相同字符:

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

 setLoading('foo') // Flow error
ESLint


ESLint将由此给出一个错误。eslint插件flowtype具有固定版本。

如果可以从初始值推断类型,则无需为Flow添加键入信息,例如:

const [open, setOpen] = React.useState(false);
type Merchandize = {|
  name: string,
  value: number,
|};

const [shoppingCare, setShoppingCart] = React.useState<Array<Merchandize>>([]);
如果由于初始值是复杂对象而无法推断,请使用泛型指定类型,例如:

const [open, setOpen] = React.useState(false);
type Merchandize = {|
  name: string,
  value: number,
|};

const [shoppingCare, setShoppingCart] = React.useState<Array<Merchandize>>([]);
类型商品={|
名称:string,
值:number,
|};
const[shoppingCare,setShoppingCart]=React.useState([]);

理想情况下,流应该从
useState(false)
(与TypeScript一样)推断类型,并且根本不需要注释似乎您需要在某些上下文中使用
加载
,否则
设置加载
将无法正常工作。如何通过“尝试流”共享流示例:?未从站点找到任何共享功能。您可以通过复制浏览器中生成的URL,通过Try Flow进行共享。您还可以使用类型参数
const[loading,setLoading]=useState(true)