【问题标题】:Why does one function cause component to rerender but the other does not Nextjs?为什么一个函数会导致组件重新呈现而另一个不会导致 Nextjs?
【发布时间】: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


    【解决方案1】:

    我假设 tempArray 还是同一个数组,也就是同一个引用。 我会将 setInvites([...tempArray]) 而不是 setInvites(tempArray) 放入 removeEmail

    【讨论】:

    • 我试试这个,谢谢建议
    • 它成功地使组件重新渲染,但由于某种原因显示的信息与实际数组不同(即)数组有项目 1 和 2。如果我删除项目 2,项目 2 消失.但是,如果我改为删除第 1 项,第 2 项仍然会消失,留下第 1 项,但 console.log() 显示第 2 项是数组中的唯一项
    • 愿意分享您修改过的代码吗?还要记住setting state is an async operation,在setInvites() 调用之后立即记录invites 不会输出更新的值。
    • @juliomalves 该建议有助于使组件重新呈现,而我剩下的错误是一个单独的问题,即 React 需要将 key prop 传递到组件中。我没有这样做,所以 React 不知道我在渲染 html 时是否改变了数组的顺序。
    【解决方案2】:

    tempArray 是对同一数组的另一个引用,即它是===

    let foo = ['a', 1, 'b']
    let bar = foo
    bar.splice(1, 1)
    
    console.log(foo, bar, foo===bar) // [ 'a', 'b' ] [ 'a', 'b' ] true
    

    你可以克隆你的数组:

    let bar = [...foo]
    

    或者使用某种不会改变原始数组的移除:

    let bar = foo.filter(f => f !== 1)
    

    在这两种情况下你都会得到

    console.log(foo, bar, foo===bar) // [ 'a', 1, 'b' ] [ 'a', 'b' ] false
    

    【讨论】:

      猜你喜欢
      • 2021-10-13
      • 1970-01-01
      • 2017-01-26
      • 1970-01-01
      • 1970-01-01
      • 2017-03-04
      • 2020-08-08
      • 1970-01-01
      • 2020-09-30
      相关资源
      最近更新 更多