简体   繁体   中英

React setState hook's previous param object gives inconsistent values

I'm using a useEffect hook to trigger a setState update. 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. Similarly when I try to access the nocolor prop it only returns an array with one string.

I can't understand. existing changes as soon as I try to access it with anything other than simply console logging it directly?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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