Can I mutate state passed to setState function?

∥☆過路亽.° 提交于 2019-12-23 08:38:33

问题


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

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

Is it a mistake to modify passed object?

EDIT:

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

state is a reference to the component state at the time the change is being applied. It should not be directly mutated. Instead, changes should be represented by building a new object based on the input from state and props

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


回答1:


A cleaner way would be to refer directly to the property you want do edit:

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



回答2:


The way you do it is not wrong. Its perfectly okk to modify the argument and then return it. However setState with prevState argument is used when you modify the state based on the value of the prevState and it prefectly fits your scenario and a more cleaner way to handle it would be

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



回答3:


It is highly discouraged to mutate the state directly. Also, you are mutating the previous state and then returnning it which doesnt make much sense. If all you want is to toggle the state at state[id] then fix your code to be more like:

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


来源:https://stackoverflow.com/questions/43305429/can-i-mutate-state-passed-to-setstate-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!