【发布时间】:2021-12-09 00:54:02
【问题描述】:
在我的 Nextjs Web 应用程序中,我的一个页面有两个函数,允许使用 nextjs 的 useState() 从数组中添加或删除电子邮件。
const [invites, setInvites] = useState([])
// other code
const lmao = () => {
console.log(invites)
}
const addEmail = async (email) => {
if(!invites.includes(email)) {
setInvites([...invites, email])
}
lmao()
}
const removeEmail = async (email) => {
let tempArray = invites
const index = tempArray.indexOf(email)
if(index > -1) {
tempArray.splice(index, 1)
}
setInvites(tempArray)
lmao()
}
函数addEmail 成功导致组件重新渲染,并且在运行时,将使用添加的电子邮件明显地更新页面。但是,函数removeEmail 无法重新呈现页面。我使用函数lmao() 看到invites 确实在根据需要进行更改,只是页面没有重新渲染以显示更改。
我还查看了Why does setState([...arr]) cause a rerender but setState(arr) does not?,它没有回答我的问题,因为在我的情况下,传递给 mutator 的项目 not === 到它以前的值,除非我是遗漏了什么。如果链接的问题确实解释了我的问题,有人可以进一步详细说明为什么 setInvites(tempArray) 即使它改变了状态值也不会导致重新渲染,以及我将如何改变我的代码来做到这一点?
【问题讨论】:
标签: javascript reactjs next.js rendering