Decorators are breaking React Router 4?
I noticed that if the app was rendered like this:
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import Router from 'react-router-dom/BrowserRouter'
import App from './App';
ReactDOM.render(
<Router>
<App />
</Router>,
document.getElementById('root')
);
// App.js
import React, { Component } from 'react';
import { BrowserRouter as Router, Link, Route } from 'react-router-dom';
import { observer } from 'mobx-react';
// Remove observer decorator to see the route changes working
@observer
class App extends Component {
render() {
return (
// I had to put `Router` in here so that my route
// changes would work when I had the @observer decorator on
// <Router>
<div>
<div>
<div><Link to="/">Home</Link></div>
<div><Link to="/a">Test 1</Link></div>
<div><Link to="/b">Test 2</Link></div>
<div><Link to="/c">Test 3</Link></div>
</div>
<div>
<Route exact path="/" render={(props) => {
return <div>home</div>
}} />
<Route path="/a" render={(props) => {
return <div>A</div>
}} />
<Route path="/b" render={(props) => {
return <div>B</div>
}} />
<Route path="/c" render={(props) => {
return <div>C</div>
}} />
</div>
</div>
// </Router>
)
}
}
export default App;
Clicking on the links would not change the route content being rendered. There is something in the observer decorator that is affecting the re-rendering of the routes. Or maybe it's a React Router issue?
Update: oh looks like it's also happening with Redux's connect as well.
Same issue here.
I checked the source code of react-router. Router triggers rendering by setState({ match }). However, connectors like observer override shouldComponentUpdate and compares only props and state. In result, the setState operation in Router doesn't trigger re-rendering in offspring nodes.
A temporary solution is to add @withRouter in EVERY component to inject routing info in props to trigger re-rendering from history changes.
Ah, using @withRouter worked.
From what package is this @withRouter ?
react-router.
is there any official fix for this? seems annoying to add this all over...
Any fix to this ? same issue here
I have the same problem.
Unless I am missing something (hard to say without small reproduction), not using withRouter is the problem. The problem is that React-router relies on any shouldComponentUpdate to be naive in your component tree otherwise to work correctly (well, the last time I checked that is, which is quite a while ago).
For extensive background to see where the issue comes from, and why Mobx can't do much about that (and why withRouter was introduced to solve the problem), read this: https://medium.com/@mweststrate/how-to-safely-use-react-context-b7e343eff076 (In the analogy, ReactRouter is like the ThemeProvider in the examples, further; same story)
If you don't think the above problem does not accurately describe your problem, please provide a small! reproduction to demonstrate the issue