Can I change the state passed to setState?

I know that I should not mutate state directly in React, but what about the situation when I use the function:

onSocialClick = e => {
    const id = e.target.value;
    this.setState((prevState, props) => {
        prevState[id] = !(prevState[id]);
        return prevState;
    });
};

Is it wrong to modify the passed object?

EDIT:

It turns out that most of us are wrong here. React docs now clearly state :

prevState is a reference to a previous state. It should not be directly mutated. Instead, changes should be presented by creating a new object based on input from prevState and props.

Thanks @ Tomáš Hübelbauer for pointing this out in the comment.

+6
source share
3 answers

, , :

doIt = () => this.setState(({ [id]: prevValue }) => ({
  [id]: !prevValue,
}));
+3

, . , , . setState prevState , prevState, ,

onSocialClick = e => {
    const id = e.target.value;
    this.setState((prevState, props) => {
        return {[id] : !(prevState[id])};
    });
};
+1

. , , . , , - state[id], , :

onSocialClick = e => {
    const id = e.target.value;
    this.setState({this.state[id]: !this.state[id});
};
-1

Source: https://habr.com/ru/post/1016418/


All Articles