[英]unnecessary re-render reactjs
所以我有這個按鈕來添加一個項目來存儲你不能添加多個但是當我點擊按鈕兩次或更多次時它會重新渲染兩個組件兩次我嘗試使用 useMemo 來記住值但它不會工作並得到e.target 中的(目標)未定義
const handleAdd = useMemo((e) => {
let newItem = {id : e.target.name, price: e.target.value, title: e.target.title, contity: 1}
item.push(newItem)
const unique = Array.from(new Set(item.map(i => i.id))).map(id =>{return item.find(i => i.id === id)})
setItem(unique)
}),[item])
useMemo 的任何解決方案或任何其他想法,以避免這種不必要的渲染..
處理來自按鈕、輸入等的事件 - 使用useCallback
鈎子。
您在鈎子內觸發 setItem 並導致重新渲染。 在鈎子中添加條件並僅在需要 id 時觸發setItem
。
這可以在沒有任何這些花哨的鈎子的情況下完成。 這是一篇關於何時使用useMemo
或useCallback
以及為什么我們大部分時間不需要它們的很棒的文章: https : useCallback
您的代碼可以在嘗試更新它之前簡單地檢查該項目是否已存在於數組中:
const handleAdd = (e) => {
const newId = e.target.name
const itemFound = item.find((i) => i.id === newId)
if (!itemFound) {
const newItem = {id : e.target.name, price: e.target.value, title: e.target.title, contity: 1}
// Using spread to avoid mutability
const updatedItem = [...item, newItem]
setItem(updatedItem)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.