[英]How to memoize a value based on a property of an object in React?
在我的功能組件中,我想記住一些取決於 object 的Id
屬性的值:
obj={
innerProperty:{
id:1
}
}
useMemo(()=>someComplaxFunction(), [obj.innerProperty.id])
我想做這樣的事情,但問題是, innerProperty
可以是undefined
。 所以我需要為innerProperty添加一個檢查,但是我不能在useMemo
之外添加它,因為它給了我一個錯誤,即不應該有條件地調用鈎子,甚至不能在內部調用,因為我將不得不添加obj
作為我不想要的依賴項,因為其他屬性可能會改變。
需要知道我怎樣才能做到這一點。 任何幫助表示贊賞。
提前致謝!
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])
在您的someComplaxFunction()
中檢查innerProperty
的值並返回類似null
的值,以便在這種情況下您記住的值是null
(或您想要的任何其他值)。 然后使用組件中的記憶值,假設它可能是null
。
猜猜你應該做一些檢查。 您不能在您的依賴數組中執行該邏輯,但您可以這樣做:
useMemo(()=> {
if (obj.innerProperty.id) {
someComplaxFunction()
}
}, [obj.innerProperty])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.