I am using react-router 2.0.0. Consider the following example:
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, IndexRoute, hashHistory } from 'react-router';
const Main = React.createClass({
getInitialState() {
return {data: 0};
},
componentDidMount() {
setInterval(() => {
console.log("Imagine I am polling data from a server here");
this.setState({data: Math.random().toFixed(2)});
}, 2000);
},
render() {
return <Router history={hashHistory}>
<Route path="/">
<IndexRoute component={MainPage} data={this.state.data}/>
<Route path="page1" component={Page1} data={this.state.data}/>
</Route>
</Router>;
}
});
const MainPage = React.createClass({
render() {
return <div>MainPage, data: {this.props.route.data}</div>;
}
});
const Page1 = React.createClass({
render() {
return <div>Page1, data: {this.props.route.data}</div>;
}
});
ReactDOM.render(<Main />, document.getElementById('app'));
My understanding of react.js is that data should usually be passed to child components as props. In the example I am polling some data from a server that should be used by two different child components. Since it is dynamic data I put it in the state.
However, if I define routing in that same component, react-router breaks down because it gets re-rendered. The updated state will not be passed to the child and the console will print:
Imagine I am polling data from a server here
Warning: [react-router] You cannot change <Router routes>; it will be ignored
One workaround that I dislike is to use global state to access the data. Which is what I did in my case.
Is there an elegant solution to this use-case?