How to keep React component state between mount/unmount?

后端 未结 8 1638
心在旅途
心在旅途 2020-12-12 18:15

I have a simple component that maintains an internal state. I have another component that toggles whether or not <

8条回答
  •  -上瘾入骨i
    2020-12-12 18:25

    I'm not an expert in React but particularly your case could be solved very cleanly without any mutable objects.

    var StatefulView = React.createClass({
      getInitialState: function() {
        return {
          count: 0
        }
      },
      inc: function() {
        this.setState({count: this.state.count+1})
      },
      render: function() {
          return !this.props.show ? null : (
            
    count:{this.state.count}
    ) } }); var App = React.createClass({ getInitialState: function() { return { show: true, component: StatefulView } }, toggle: function() { this.setState({show: !this.state.show}) }, render: function() { return (
    ) } }); ReactDOM.render( , document.getElementById('container') );

    You can see it at jsfiddle.

提交回复
热议问题