How can i keep state in a React component using ES6

前端 未结 4 1233
生来不讨喜
生来不讨喜 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 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});
    }
    

提交回复
热议问题