函数createHiveBackground
返回我要分配给状态的对象数组。稍后在我的应用程序中,我将使用setHive
更改数组的某些值。这些有什么区别?
const [hive, setHive] = React.useState(createHiveBackground);
const [hive, setHive] = React.useState(createHiveBackground());
const [hive, setHive] = React.useState(()=>createHiveBackground);
const [hive, setHive] = React.useState(()=>createHiveBackground());
如果我使用
useState(createHiveBackground)
,它似乎可以正常工作。如果每次使用setHive更改值时都使用
useState(createHiveBackground())
,则会再次调用该函数。如果我使用
useState(()=>createHiveBackground)
TypeError:hive.map不是函数(似乎该函数未在执行)。如果我使用
React.useState(()=>createHiveBackground());
,它似乎可以正常工作。可以澄清一下所有这些选项之间的区别是什么?
最佳答案
区别在于:
// Lazy assign the return value of the function
// Both are equivalent as First-class functions (check the reference)
const [hive, setHive] = React.useState(createHiveBackground);
const [hive, setHive] = React.useState(() => createHiveBackground());
// Assign the return value from the function
const [hive, setHive] = React.useState(createHiveBackground());
// Lazy assign the function
const [hive, setHive] = React.useState(() => createHiveBackground);
引用文献:
关于javascript - useState(function_name),useState(function_name()),useState(()=> function_name())和useState(()=> function_name)之间有什么区别?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58470679/