How can i keep state in a React component using ES6

前端 未结 4 1209
生来不讨喜
生来不讨喜 2020-12-22 09:25

I\'m trying to use a stateful React component with ES6 but when I define a constructor the constructor will only be called once while the component is rendered multiple time

相关标签:
4条回答
  • 2020-12-22 09:57

    My bad, I thought that the constructor (or getInitialState for ES5) is called whenever the component is being re-rendered by the parent (I thought that the parent 're-creates' its children on render) but that's not always the case. I should had read up on it (url) and tried it with ES5 (jsFiddle) before thinking it was something I didn't understand with ES6 and creating a question here.

    And yes, the example SubComponent should use this.props but my use case had actual stateful functionality in my real component. I created the example as I thought for some reason that the result weren't the expected outcome when using ES6 (but it was).

    Thank you for you feedback!

    0 讨论(0)
  • 2020-12-22 10:04

    I recommend to read Props in getInitialState Is an Anti-Pattern.

    Basically, as few components as possible should have state. As the other answers already said, in your case you can just use this.props.count to refer to the current value. There doesn't seem to be any reason why SubComponent should have its own state.

    However, if you really want to compute the component's state from the props it receives, it is your responsibility to keep them in sync, with the life cycle method componentWillReceiveProps:

    componentWillReceiveProps(nextProps) {
        this.setState({count: nextProps.count});
    }
    
    0 讨论(0)
  • 2020-12-22 10:04

    In SubComponent it is props not state - change it to this.props.count and this will work

    0 讨论(0)
  • 2020-12-22 10:04

    You SubComponent should be:

     class SubComponent extends React.Component {
          constructor(props) {
            super(props);
            console.log("Creating sub component");
          }
    
          render() {
            return (<div>count: {this.props.count}</div>);
          }
        }
    
    0 讨论(0)
提交回复
热议问题