当涉及到React-Router组件时,我很笨拙。但是,当我浏览链接时,我无法解释为什么我的组件会被卸载?以及如何预防?
在我的示例中,我有一个包含计时器和重新渲染内容的组件
我有一个错误:
这是 ReactJS 代码:
/*global define, Backbone, React, $, Request, Router, Route, Link */
var App = React.createClass({
render: function () {
return (
<div>
<h1>App</h1>
<ul>
<li><Link to="/about">About</Link></li>
<li><Link to="/timer">Timer</Link></li>
</ul>
{this.props.children}
</div>
)
}
});
var About = React.createClass({
render: function () {
return <h3>Here is about page</h3>
}
});
var Timer = React.createClass({
getInitialState: function() {
return {counter: 0};
},
render: function () {
return (
<div>
<h2>Time is running over...</h2>
<b>{this.props.interval}</b>
<p>{this.state.counter}</p>
</div>
)
},
componentDidMount: function () {
this.loadCommentsFromServer();
setInterval(this.loadCommentsFromServer, 1000);
},
loadCommentsFromServer: function () {
this.setState({counter: this.state.counter + 1});
}
});
React.render((
<Router location="history">
<Route path="/" component={App}>
<Route path="about" component={About} />
<Route path="timer" component={Timer} />
</Route>
</Router>
), document.body);