我正在使用React和React-Router用于具有导航的水疗中心。路由器每次切换导航项目时都会调用React组件为"构造函数"。这是代码的相关位:
class Home extends React.Component {
constructor(props) {
super(props);
console.log('component constructed!');
this.state = {
counter: 0
}
setInterval(() => this.setState({
counter: this.state.counter+1
}), 1000)
}
render() {
return (
<h3>Counter: {this.state.counter}</h3>
);
}
}
ReactDOM.render(
<Router history={hashHistory}>
<Route path="/" component={App}>
<IndexRoute component={Home} />
<Route path="profile" component={Profile} />
<Route path="settings" component={Settings} />
</Route>
</Router>,
document.getElementById('container')
);
每当我从一个选项卡切换到另一个选项卡时,计数器从0开始。显然,我知道每当其状态更改或路由器切换选项卡时都应调用render()
,但是为什么要调用constructor
以更改选项卡?这是React-Router的工作方式,还是我做错了什么?
此处问了这个问题,但是所接受的答案谈论了"重新渲染",而不是重新构建组件。
每次组件安装时都会调用构造函数。每次导航到位置/
时,<Home>
组件都会安装。当您导航到另一个位置时,<Home>
组件将卸载。如果您希望状态在整个导航中持续存在,则应将其保持在树上。