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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…