函数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);
    

    引用文献:
  • useState Hook
  • Lazy initial state
  • First Class Function
  • 关于javascript - useState(function_name),useState(function_name()),useState(()=> function_name())和useState(()=> function_name)之间有什么区别?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58470679/

    10-12 00:10