简体   繁体   English

不必要的重新渲染 reactjs

[英]unnecessary re-render reactjs

so i have this button to add an item to store u cant add more than one but when i click on the button twice or more it keep re-render two components twice i tried to use useMemo to memorize the value but it wont work and get the (target) from e.target is undefined所以我有这个按钮来添加一个项目来存储你不能添加多个但是当我点击按钮两次或更多次时它会重新渲染两个组件两次我尝试使用 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])

any solution for useMemo or any other idea to avoid this unnecessary render .. useMemo 的任何解决方案或任何其他想法,以避免这种不必要的渲染..

  • to handle event's from buttons, inputs etc - use useCallback hook.处理来自按钮、输入等的事件 - 使用useCallback钩子。

  • you trigger setItem inside your hook and it causes re-render.您在钩子内触发 setItem 并导致重新渲染。 Add condition inside your hook and trigger setItem only when id needed.在钩子中添加条件并仅在需要 id 时触发setItem

This could be done without any of these fancy hooks.这可以在没有任何这些花哨的钩子的情况下完成。 Here is a great article about when to use useMemo or useCallback and why we don't need those most of the time: https://kentcdodds.com/blog/usememo-and-usecallback这是一篇关于何时使用useMemouseCallback以及为什么我们大部分时间不需要它们的很棒的文章: https : useCallback

Your code could simply check if the item already exists in the array before trying to update it:您的代码可以在尝试更新它之前简单地检查该项目是否已存在于数组中:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM