javascript - How to keep React component state between mount/unmount? -
i have simple component <statefulview>
maintains internal state. have component <app>
toggles whether or not <statefulview>
rendered.
however, want keep <statefulview>
's internal state between mounting/unmouting.
i figured instantiate component in <app>
, control whether 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 , new <statefulview>
created on each toggle.
here's jsfiddle.
is there way hang on same component after unmounted can re-mounted?
i thinking bit.
i've put attempts in repo: react-keep-state.
for me, suitable solution following:
import react, { component, proptypes } 'react'; // set initial state let state = { counter: 5 }; class counter extends component { constructor(props) { super(props); // retrieve last state this.state = state; this.onclick = this.onclick.bind(this); } componentwillunmount() { // remember state next mount state = this.state; } onclick(e) { e.preventdefault(); this.setstate(prev => ({ counter: prev.counter + 1 })); } render() { return ( <div> <span>{ this.state.counter }</span> <button onclick={this.onclick}>increase</button> </div> ); } } export default counter;
please see repo discussion (and solution uses higher order components).
Comments
Post a Comment