D
D
DonorOfLove2021-11-30 10:46:47
React
DonorOfLove, 2021-11-30 10:46:47

Why is a separate state property not set?

*code slightly simplified for readability*

there is a state:
[user,setUser]=React.useState({
        name: 'noName',
        pull: [{},{},{}],
    })

there is a component:
<Hero addToCamp={() => addToCamp()/>)
which, when clicked, calls a function that should only be set by pull:
const addToCamp = () => {
            let newHeroes= ...
            setUser({pull: newHeroes}) // Что тут не так?..
        }
    }

Question: am I stupid or the sleigh doesn't go? Explain to the narrow-minded - why is it so, why, with a set, newHeroes overwrites the entire state. I looked at several resources, only such a method of setting a separate property is described everywhere, yes, it would be possible to create a copy of the user, then replace the desired property in it and already set this copy, but for me this is not entirely valid. I would love your help :3

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexandroppolus, 2021-11-30
@DonorOfLove

In class components, this.setState superficially submerged the passed value into the state. In a hook, it simply replaces, and you need to merge manually, for example, through spreads. That's the way the world works. There is only one state in the class, and there can be several useState. For example here one could do useState for name and useState for pull

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question