简体   繁体   English

为什么组件不重新渲染?

[英]Why component doesn't rerender?

const [dammy, setDammy] = useState({
  name: "any",
  status: {
    "1.0.1": "Successfylly installed",
    "1.0.2": "Successfylly installed",
    "1.0.3": "Successfylly installed",
    "1.0.4": "Successfylly installed",
    "1.0.6": "Installing",
    "1.0.7": "In Queue",
    "1.0.8": "In Queue",
    "1.1.1": null,
    "1.1.2": null,
    "1.1.36": null,
    "1.1.4": null,
    "1.1.5": null,
    "1.1.6": null,
  },
  available: ["1.1.1", "1.1.2", "1.1.36", "1.1.4", "1.1.5", "1.1.6"],
  queue: ["1.0.7", "1.0.8"],
  date: new Date()
})

function addingToQueue(e: MouseEvent < HTMLDivElement > , i: number) {
  setDammy(prev => {
    let val = prev["available"].splice(i, 1)
    prev["queue"].push(val[0])
    console.log(prev) // <-- I could see changes has been applied
    return prev
  })
}

component doesn't rerender even tho I could see that in setDummy console show's the right object data.即使我可以在 setDummy 控制台中看到正确的对象数据,组件也不会重新渲染。 But after completing function pre-render doesn't happen and on a screen I see no changes.但是在完成功能预渲染后不会发生,并且在屏幕上我看不到任何变化。

Because you're not actually returning a new array in your callback to setDammy -- you're merely mutating the previous one and returning it;因为您实际上并没有在setDammy的回调中返回一个新数组——您只是改变了前一个数组并返回它; when React does its comparison, it will see that the returned object is still the same reference.当 React 进行比较时,它会看到返回的对象仍然是同一个引用。 Instead, spread into a new array and alter that :相反,传播到一个新数组并改变

setDammy(prev => {
  const newArr = [...prev];
  let val = newArr["available"].splice(i, 1)
  newArr["queue"].push(val[0])
  console.log(newArr) // <-- I could see changes has been applied
  return newArr
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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