问题
I am writing a small app with a navigation bar and 5 routes using react-router-dom 4.1.1. When I click on a link in the navigation bar, the URL in the Firefox address bar updates, but the page displayed does not change. However, if I enter the address of a subpage in the address bar, the correct page is displayed.
app.js:
render(
<Provider store={store}>
<HashRouter>
<MainContainer />
</HashRouter>
</Provider>,
document.querySelector('.app')
);
Main.js:
render() {
return (
<div className="main">
<Message message= {this.props.message} />
<NavigationBar />
<Switch>
<Route exact path="/" component={HomePage}></Route>
<Route path="/classify" component={ClassifyPage}></Route>
<Route path="/admin" component={AdminPage}></Route>
<Route path="/users" component={UsersPage}></Route>
<Route path="/help" component={HelpPage}></Route>
</Switch>
</div>
);
}
回答1:
It seems some components, like react-redux containers using connect(), block updates. The problem was solved using withRouter():
const MainContainer = withRouter(connect(
mapStateToProps,
mapDispatchToProps
)(Main));
Documentation: https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/withRouter.md
回答2:
I have the same error, but when I use withRouter, nothing changes. In my case, the reason of error is putting the <Link> elements into the <Router> tag.
<Router>
<Link to="something"></Link>
</Router>
Beware of that error, is very hard to diagnose! To fix this, just remove unneccesary <Router> wrapper
回答3:
Erik Winge almost the right. As I understand component where you enter you need to wrap your Component with withRouter.
So, to fix this you need to add:
...
Main = withRouter(Main);
...
export default Main;
...
来源:https://stackoverflow.com/questions/44823590/react-router-4-doesnt-update-ui-when-clicking-link