如何根据 React 中对象的 属性 记忆一个值?

How to memoize a value based on a property of an object in React?

在我的功能组件中,我想记住一些取决于对象的 Id 属性 的值:

obj={
  innerProperty:{
    id:1
  }
}
useMemo(()=>someComplaxFunction(), [obj.innerProperty.id])

我想做这样的事情,但问题是,innerProperty 可以是 undefined。所以我需要为 innerProperty 添加一个检查,但我不能在 useMemo 之外添加它,因为它给我错误,即不应该有条件地调用钩子,甚至不应该在内部调用,因为我将不得不添加 obj 作为我不想要的依赖项,因为其他属性可能会改变。

需要知道我怎样才能做到这一点。 感谢任何帮助。

提前致谢!

在你的 someComplaxFunction() 中检查 innerProperty 和 return 的值,比如 null 这样你记住的值是 null 在这种情况下(或者你想要的任何其他东西)。然后在你的组件中使用记忆值,假设它可能是 null.

我猜你应该做一些检查。您不能在依赖项数组中执行该逻辑,但您可以这样做:

useMemo(()=> {
    if (obj.innerProperty.id) {
        someComplaxFunction()
    }
}, [obj.innerProperty])
obj={
  innerProperty:{
    id:1
  }
}
const id = obj.innerProperty ? obj.innerProperty.id : undefined

// or using optional chaining(?.)
const id = obj.innerProperty?.id

useMemo(()=>someComplaxFunction(id), [id])