Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a simple component <StatefulView> that maintains an internal state. I have another component <App> that toggles whether or not <StatefulView> is rendered.

However, I want to keep <StatefulView>'s internal state between mounting/unmouting.

I figured I could instantiate the component in <App> and then control whether its rendered/mounted.

var StatefulView = React.createClass({
  getInitialState: function() {
    return {
      count: 0
    }
  },
  inc: function() {
    this.setState({count: this.state.count+1})
  },
  render: function() {
    return (
        <div>
          <button onClick={this.inc}>inc</button>
          <div>count:{this.state.count}</div>
        </div>
    )
  }
});

var App = React.createClass({
  getInitialState: function() {
    return {
      show: true,
      component: <StatefulView/>
    }
  },
  toggle: function() {
    this.setState({show: !this.state.show})
  },
  render: function() {
    var content = this.state.show ? this.state.component : false
    return (
      <div>
        <button onClick={this.toggle}>toggle</button>
        {content}
      </div>
    )
  }
});

This apparently doesnt work and a new <StatefulView> is created on each toggle.

Here's a JSFiddle.

Is there a way to hang on to the same component after it is unmounted so it can be re-mounted?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
703 views
Welcome To Ask or Share your Answers For Others

1 Answer

Since you can't keep the state in the component itself when it unmounts, you have to decide where else it should be saved.

These are your options:

  1. React state in parent: If a parent component remains mounted, maybe it should be the owner of the state or could provide an initial state to an uncontrolled component below. You can pass the value back up before the component unmounts. With React context you can hoist the state to the very top of your app (see e.g. unstated).
  2. Outside of React: E.g. use-local-storage-state. Note that you might need to manually reset the state inbetween tests. Other options are query params in the URL, state management libraries like MobX or Redux, etc.

I've you're looking for an easy solution where the data is persisted outside of React, this Hook might come in handy:

const memoryState = {};

function useMemoryState(key, initialState) {
  const [state, setState] = useState(() => {
    const hasMemoryValue = Object.prototype.hasOwnProperty.call(memoryState, key);
    if (hasMemoryValue) {
      return memoryState[key]
    } else {
      return typeof initialState === 'function' ? initialState() : initialState;
    }
  });

  function onChange(nextState) {
    memoryState[key] = nextState;
    setState(nextState);
  }

  return [state, onChange];
}

Usage:

const [todos, setTodos] = useMemoryState('todos', ['Buy milk']);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...