简体   繁体   English

React setState hook 的前一个 param 对象给出了不一致的值

[英]React setState hook's previous param object gives inconsistent values

I'm using a useEffect hook to trigger a setState update.我正在使用useEffect钩子来触发 setState 更新。 I'm getting some strange and inconsistent behaviour from the previous param:我从上一个参数中得到了一些奇怪且不一致的行为:

    useEffect(() => {
        setCurrentPicturesObject((existing) => {
            const clone = {...existing}
            console.log({
                existing,
                existingdotNocolor: existing.nocolor,
                selectedColorState,
                selectedColorArray: existing["nocolor"],
                clone
            });
            return existing
        });
    }, [selectedColorState]);

So you'd expect that the clone of the object would return an object with the same keys and values, right?所以你会期望对象的克隆会返回一个具有相同键和值的对象,对吗? Not here:不在这里:

控制台日志截图

Somehow existing goes from being an object with a nocolor prop with an array of two strings, to switching to an array with one string.以某种方式existing从一个带有两个字符串数组的nocolor的对象切换到一个带有一个字符串的数组。 Similarly when I try to access the nocolor prop it only returns an array with one string.同样,当我尝试访问nocolor道具时,它只返回一个包含一个字符串的数组。

I can't understand.我无法理解。 existing changes as soon as I try to access it with anything other than simply console logging it directly?一旦我尝试使用除直接控制台记录之外的任何其他方式访问它时, existing更改?

Not entirely sure on the details, but essentially it seems that the console is logging a live view of the object, which is a static string.不完全确定细节,但基本上似乎控制台正在记录对象的实时视图,这是一个静态字符串。 More info in this answer .此答案中的更多信息。

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

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