亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

不必要的重新渲染reactjs

不必要的重新渲染reactjs

侃侃無極 2023-08-24 18:04:16
所以我有這個按鈕來添加一個項目來存儲,你不能添加多個項目,但是當我單擊該按鈕兩次或多次時,它會重新渲染兩個組件兩次,我嘗試使用 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 的任何解決方案或任何其他想法來避免這種不必要的渲染..
查看完整描述

1 回答

?
狐的傳說

TA貢獻1804條經驗 獲得超3個贊

這可以在沒有任何這些花哨的鉤子的情況下完成。

您的代碼可以在嘗試更新之前簡單地檢查該項目是否已存在于數組中:

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)

? }

}


查看完整回答
反對 回復 2023-08-24
  • 1 回答
  • 0 關注
  • 178 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號