基本上,我要做的是在代码的一部分中调用这个'myMemoFunction'
函数。问题是,根据我在文档中读到的内容,useMemo()
在渲染时立即执行此函数,因此myArray
参数仍然为空。然后返回下面的错误。
const myMemoFunction = useMemo((myArray) => {
const users = myArray.map((a) => a.user)
return users;
})
错误:
myArray未定义
在这种情况下应该使用useCallback
因为CCD_ 5存储变量。我也怀疑这是否需要争论。
编辑:
const myMemoFunction = useCallback((myArray) => {
// this won't be called on renders
const users = myArray.map((a) => a.user)
return users;
}, [] /* dont forget the dependency you want to evaluate only once */)
// later
myMemoFunction(arr);
使用编辑2备注:
const myMemoVariable = useMemo(() => {
// re-evaluates each time myArray changes
const users = myArray.map((a) => a.user)
return users;
}, [myArray])
// note that we dont use myMemoVariable() to get our variable
console.log(myMemoVariable)
将您的代码更新到此
const myMemoFunction = useMemo((myArray) => {
// myArray could be undefined, that was why ? was added
const users = myArray?.map((a) => a.user)
return users;
}, [myArray]) // myArray is in a dependency of the function
您的备忘录功能将使用新的myArray变量进行更新
将myArray变量初始化为数组总是很好的,例如[]