How to keep React component state between mount/unmount?

后端 未结 8 1639
心在旅途
心在旅途 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条回答
  •  北海茫月
    2020-12-12 18:38

    OK. So after talking with a bunch of people, it turns out that there is no way to save an instance of a component. Thus, we HAVE to save it elsewhere.

    1) The most obvious place to save the state is within the parent component.

    This isn't an option for me because I'm trying to push and pop views from a UINavigationController-like object.

    2) You can save the state elsewhere, like a Flux store, or in some global object.

    This also isn't the best option for me because it would be a nightmare keeping track of which data belongs to which view in which Navigation controller, etc.

    3) Pass a mutable object to save and restore the state from.

    This was a suggestion I found while commenting in various issue tickets on React's Github repo. This seems to be the way to go for me because I can create a mutable object and pass it as props, then re-render the same object with the same mutable prop.

    I've actually modified it a little to be more generalized and I'm using functions instead of mutable objects. I think this is more sane -- immutable data is always preferable to me. Here's what I'm doing:

    function createInstance() {
      var func = null;
      return {
        save: function(f) {
          func = f;
        },
        restore: function(context) {
          func && func(context);
        }
      }
    }
    

    Now in getInitialState I'm creating a new instance for the component:

    component: 
    

    Then in the StatefulView I just need to save and restore in componentWillMount and componentWillUnmount.

    componentWillMount: function() {
      this.props.instance.restore(this)
    },
    componentWillUnmount: function() {
      var state = this.state
      this.props.instance.save(function(ctx){
        ctx.setState(state)
      })
    }
    

    And that's it. It works really well for me. Now I can treat the components as if they're instances :)

提交回复
热议问题