简体   繁体   English

在 React 中,为什么 setTimeout 中的 setState 只能与 state 的副本一起正常工作?

[英]In React, why does setState in a setTimeout only work properly with a copy of the state?

In my code below, I placed setCards inside a setTimeout but after 1 second the render will only be correct if I pass in a copy of the state: [...cardStates] rather than cardStates itself.在下面的代码中,我将 setCards 放在 setTimeout 中,但只有在我传入 state: [...cardStates] 而不是 cardStates 本身的副本时,渲染才会正确。 If I don't do this, the setCards will render the cardStates as it was before hideCards() made changes to the state.如果我不这样做,setCards 将呈现 cardStates,就像 hideCards() 对 state 进行更改之前一样。

I think this has something to do with the state when setTimeout places the function in the queue but I don't fully grasp what's happening.当 setTimeout 将 function 放入队列时,我认为这与 state 有关,但我不完全了解发生了什么。 I've dug around a lot and things like stale closures came up but I'm not sure if this is the correct direction.我已经挖掘了很多,并且出现了诸如过时的关闭之类的事情,但我不确定这是否是正确的方向。 Can someone help clear this up for me?有人可以帮我解决这个问题吗? Thank you.谢谢你。

useEffect(() => {
        if (numberShowing(cardStates) === 2) {
            setTimeout(() => {
                setCards(hideCards([...cardStates]));
            }, 1000)
        }
    })

function hideCards(cards) {
    let showing = cards.filter(card => {
        return card.cardState === 'showing';
    })
    showing.forEach(card => {
        card.cardState = 'hiding';
    });
    return cards;
}

Because a state is immutable, you can't manipulate it directly.因为 state 是不可变的,所以不能直接操作它。 Try to debug something with mutable data, in some case it can become painful.尝试用可变数据调试某些东西,在某些情况下它会变得很痛苦。

That's not the only benefit to immutability but i won't do better explanation than you can already find on internet;).这不是不变性的唯一好处,但我不会做比您在互联网上已经找到的更好的解释;)。

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

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