I'm using react and react-router for a SPA which has a navigation. The router is calling the react ponent 'constructor' every time a navigation item is switched. Here is the relevant bit of code:
class Home extends React.Component {
constructor(props) {
super(props);
console.log('ponent 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="/" ponent={App}>
<IndexRoute ponent={Home} />
<Route path="profile" ponent={Profile} />
<Route path="settings" ponent={Settings} />
</Route>
</Router>,
document.getElementById('container')
);
Every time I switch from one tab to another, the counter starts from 0.
Obviously I understand that render()
should be called every time its state changes or when router switches tabs, but why call constructor
for change of tab?! Is that how react-router works, or am I doing something wrong?
This question has been asked here, but the accepted answer talks about 're-rendering' and not re-construction of the ponent.
I'm using react and react-router for a SPA which has a navigation. The router is calling the react ponent 'constructor' every time a navigation item is switched. Here is the relevant bit of code:
class Home extends React.Component {
constructor(props) {
super(props);
console.log('ponent 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="/" ponent={App}>
<IndexRoute ponent={Home} />
<Route path="profile" ponent={Profile} />
<Route path="settings" ponent={Settings} />
</Route>
</Router>,
document.getElementById('container')
);
Every time I switch from one tab to another, the counter starts from 0.
Obviously I understand that render()
should be called every time its state changes or when router switches tabs, but why call constructor
for change of tab?! Is that how react-router works, or am I doing something wrong?
This question has been asked here, but the accepted answer talks about 're-rendering' and not re-construction of the ponent.
Share Improve this question edited May 23, 2017 at 10:32 CommunityBot 11 silver badge asked Nov 24, 2016 at 20:24 mavilimavili 3,4244 gold badges32 silver badges46 bronze badges1 Answer
Reset to default 6The constructor is called every time that a ponent mounts. Each time that you navigate to the location /
, the <Home>
ponent will mount. When you navigate to another location, the <Home>
ponent will unmount. If you want the state to be persistent across navigation, it should be kept higher up the tree.