我有一个名为 的函数获取所有员工 我从另一个文件中导出。
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]
我的问题是为什么他们给我相同的结果,这是正确的方法?
最佳答案
Why they gives me same results?
const [result] = useState(getAllEmployees)
react useState
hook 可以采用惰性初始化函数,当组件正在挂载和状态正在初始化时被调用。您正在传递一个回调,以便 React 调用并使用返回值初始化状态。const [result] = useState(getAllEmployees())
这只是立即调用函数并将返回值传递给钩子(Hook)以作为初始状态。const [result] = useState(() => getAllEmployees())
这与 1 相同,但您传递了一个匿名初始化函数。Which is the right way?
正确的方法是适用于您的用例、易于阅读、理解和维护的方法。 1 或 2 都可以,如果很明显
getAllEmployees
则为 1是一个函数,如果不是,则为 2。 3是不必要的。
关于javascript - React 默认调用不带括号的函数 useState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66238443/