热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

React默认调用不带括号的函数useState

我有一个名为getAllEmployees的函数,我从另一个文件中导出它。constgetAllEmployees=()

我有一个名为getAllEmployees的函数,我从另一个文件中导出它。

const getAllEmployees = () => {
return [1,2,3,4,5,6,7,8,9]
}
export { getAllEmployees }

现在我使用React.useState(getAllEmployees)。这给了我结果,当我像React.useState(getAllEmployees())这样调用时它也给我相同的结果,当像React.useState(() => getAllEmployees())这样的调用时它也给了我相同的结果。

在这里导入

import { getAllEmployees } from './Service/Service'

与 useState 一起使用

const [result] = useState(getAllEmployees ) or
const [result] = useState(getAllEmployees()) or
const [result] = useState(() => getAllEmployees())
console.log(result)

因为所有这些结果是

(9) [1, 2, 3, 4, 5, 6, 7, 8, 9]

我的问题是为什么他们给我相同的结果,哪个是正确的方法?

回答



为什么他们给我相同的结果?



  1. const [result] = useState(getAllEmployees)

    React useStatehook 可以采用惰性初始化函数,在组件挂载和状态初始化时调用。您正在传递一个回调以供 React 调用并使用返回值初始化状态。


  2. const [result] = useState(getAllEmployees())

    这只是立即调用函数并将返回值传递给钩子作为初始状态。


  3. const [result] = useState(() => getAllEmployees())

    这与 1 相同,但您传递了一个匿名初始化函数。



哪个是正确的方法?

正确的方法是适合您的用例的方法,易于阅读、理解和维护。1 或 2 没问题,如果很明显这getAllEmployees是一个函数,则为1,如果不是,则为 2。3 是不必要的。






推荐阅读
author-avatar
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有