react-router4.0 link组件只有路由变化页面不能跳转

新手上路,请多包涵

为了实现路由为

<App>
    <LFMusic/>
    /*<LFCollections/>*/
</App>

的效果,我遇见了下面的问题:

当Route组件父元素为div等元素时link可以正常跳转,而为自定义组件时只有路由变化,页面不跳转刷新。这是route父元素为自定义组件的情况

    <Router history={history}>
        <App>
            <Route path="/" component={LFMusic} exact/>
            <Route path="/mycollections" component={LFCollections}/>
        </App>
    </Router>

clipboard.png
而需要手动刷新浏览器才可以正常显示

clipboard.png
但是当route父元素为div时,点击link可以直接跳转并刷新。对了link组件在App子组件LFMusic中下面是route父元素为div的情况

    <Router history={history}>
        <div>
            <Route path="/" component={LFMusic} exact/>
            <Route path="/mycollections" component={LFCollections}/>
        </div>
    </Router>
    

clipboard.png

求助,萌新已经懵逼了。

阅读 20.5k
7 个回答

同样踩了这个坑.
原因是 <Route> 和 <Link> 没有在同一个 <Router> 下.
解决方案: 将 <Route> 和 <Link> 放在同一个 <Router> 标签内.
如下:

<Router history={history}>
    <div>
        <Route path="/" component={LFMusic} exact/>
        <Route path="/mycollections" component={LFCollections}/>
    </div>
    <div>
        <Link to="/"></Link>
        <Link to="/mycollections"></Link>
    </div>
</Router>

这个原因应该是 App.js 中使用了 redux 的缘故。

解决方案:给 App 包上 withRouter 即可

import {withRouter} from 'react-router-dom' ;

...

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(App));

当然,这里解决方案不止一种,如果我说的不能解决你的问题,或者你想探究更多,可以参考:
https://stackoverflow.com/que...

好吧已经解决。是我逗了,没有exact全部匹配根路径了也就是‘/’

新手上路,请多包涵

我好像跟你遇到一样的问题了,我把App改成div也是好了,但是我要用上App,exact我也写了,貌似还是不行哇~~图片描述

新手上路,请多包涵

你这个问题怎么解决的啊

我解决了, App组件在export的时候加上withRouter

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进