Is it a good practice to modify a component's state and then call “setState(this.state)”?

后端 未结 3 931
不思量自难忘°
不思量自难忘° 2021-01-22 06:52

I\'m using ReactJS.

I have a statefull component (stopwatch container) and multiple child components which are stateless (stopwatches).

In the outer component,

相关标签:
3条回答
  • 2021-01-22 07:07

    Instead of calling this.setState(this.state) you can just call this.forceUpdate().

    Just remember that this is not recommended way of updating components state. If you are unsure about your modifications take a look on Immutability Helpers.

    0 讨论(0)
  • 2021-01-22 07:20

    Just my two cents here: react will re-render everytime you call setState, boolean shouldComponentUpdate(object nextProps, object nextState) returns true by default. If you don't wish to re-render make shouldComponentUpdate(object nextProps, object nextState) to return false.

    Quoting from facebook docs: By default, shouldComponentUpdate always returns true to prevent subtle bugs when state is mutated in place, but if you are careful to always treat state as immutable and to read only from props and state in render() then you can override shouldComponentUpdate with an implementation that compares the old props and state to their replacements.

    0 讨论(0)
  • 2021-01-22 07:24

    Aside from immutability (which is always good), the second best would be this.setState({stopwatches: this.state.stopwatches}).

    With immutability helpers, it'd look like this:

    var stopwatches = this.state.stopwatches.map(function(watch){
      return update(watch, {
        time: {$set: watch.time + 1}
      });
    });
    this.setState({stopwatches: stopwatches})
    

    Or with es6 you can save a few characters.

    var stopwatches = this.state.stopwatches.map(watch => update(watch, {
        time: {$set: watch.time + 1}
    });
    this.setState({stopwatches})
    
    0 讨论(0)
提交回复
热议问题