作者: | 来源:互联网 | 2023-09-07 12:24
我有一个名为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]
我的问题是为什么他们给我相同的结果,哪个是正确的方法?
回答
为什么他们给我相同的结果?
const [result] = useState(getAllEmployees)
React useState
hook 可以采用惰性初始化函数,在组件挂载和状态初始化时调用。您正在传递一个回调以供 React 调用并使用返回值初始化状态。
const [result] = useState(getAllEmployees())
这只是立即调用函数并将返回值传递给钩子作为初始状态。
const [result] = useState(() => getAllEmployees())
这与 1 相同,但您传递了一个匿名初始化函数。
哪个是正确的方法?
正确的方法是适合您的用例的方法,易于阅读、理解和维护。1 或 2 没问题,如果很明显这getAllEmployees
是一个函数,则为1,如果不是,则为 2。3 是不必要的。