How to keep React component state between mount/unmount?

后端 未结 8 1637
心在旅途
心在旅途 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:36

    If you want to be able to unmount and mount while maintaining state, you will need to store the count in App and pass down the count via props.

    (When doing this, you should be calling a toggle function inside of App, you want the functionality which changes data to live with the data).

    I will modify your fiddle to be functional and update my answer with it.

    0 讨论(0)
  • 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: <StatefulView instance={createInstance()}/>
    

    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 :)

    0 讨论(0)
提交回复
热议问题