React - Changing the state without using setState: Must avoid it?

后端 未结 4 2002
轮回少年
轮回少年 2020-12-19 02:55

My code works, but I have a best practice question: I have an array of objects in the state, and a user interaction will change a value of one object at a time. As far a

4条回答
  •  情深已故
    2020-12-19 03:23

    Personally I don't always follow the rule, if you really understand what you are trying to do then I don't think it's a problem.

    var data = this.state.data.slice(0);
    data[index].is_collected = !data[index].is_collected;
    this.setState({data: data});
    

    In this case, mutating state and calling the setState again like this is fine

    this.state.data[index].is_collected = !this.state.data[index].is_collected;
    this.setState({data: this.state.data});
    

    The reason you should avoid mutating your state is that if you have a reference to this.state.data, and calling setState multiple times, you may lose your data:

    const myData = this.state.data
    myData[0] = 'foo'
    this.setState({ data: myData })
    // do something...
    // ...
    const someNewData = someFunc()
    this.setState({ data: someNewData })
    
    myData[1] = 'bar' // myData is still referencing to the old state
    this.setState({ data: myData }) // you lose everything of `someNewData`
    

    If you really concerned about this, just go for immutable.js

提交回复
热议问题