为什么组件不重新渲染?
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
})
}
即使我可以在 setDummy 控制台中看到正确的对象数据,组件也不会重新呈现。但是在完成功能后预渲染不会发生并且在屏幕上我看不到任何变化。
因为您实际上并没有在回调中返回一个新数组给 setDammy
-- 您只是改变前一个数组并返回它;当 React 进行比较时,它会发现返回的对象仍然是同一个引用。相反,传播到一个新数组中并改变 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
})
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
})
}
即使我可以在 setDummy 控制台中看到正确的对象数据,组件也不会重新呈现。但是在完成功能后预渲染不会发生并且在屏幕上我看不到任何变化。
因为您实际上并没有在回调中返回一个新数组给 setDammy
-- 您只是改变前一个数组并返回它;当 React 进行比较时,它会发现返回的对象仍然是同一个引用。相反,传播到一个新数组中并改变 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
})