簡體   English   中英

路由器已更改,但組件未重新呈現

[英]router changed but component does not rerender

我正在使用react-router v4和redux。 我有一個類似的反應路由器事件

//src/App/components/common/Notifications
onCommentClick = (id) => {
    this.props.history.push(`/dashboard/${id}`)
}

它將更改瀏覽器網址,我的路由設置正確,我猜

//src/App/containers/dashboard/user/NotificationDetail
renderUserRoute() {
    return (
      <Switch>
        <Route exact path="/dashboard" component={UserAreaGuarded} />
        <Route exact path="/dashboard/:id" component={NotificationDetail} />
      </Switch>
    )
  }

但是問題是redux似乎沒有重新渲染我的容器組件,我需要刷新以獲取正確的內容。

我創建了一個倉庫來演示這個問題, https://github.com/thian4/hoc-redux ,為此已經被擱置了很長時間,找不到任何線索,說明它為什么不重新渲染。

問題不在於路由器, NotificationDetail組件僅在componentDidMount調用fetchNotification 使用Route component prop渲染路線組件時NotificationDetail路線組件僅安裝一次,然后僅在每次重新渲染時進行更新。

有兩種方法可以解決此問題...

  1. NotificationDetail ,在componentDidUpdate而不是componentdidMount執行fetchNotification東西,只需重命名該方法即可。 這種方法更好。

  2. 使用無狀態組件作為dashboard\\index.jscomponent prop的值:

     renderUserRoute() { return ( <Switch> <Route exact path="/dashboard" component={UserAreaGuarded} /> <Route exact path="/dashboard/:id" component={props => <NotificationDetail {...props} />} /> </Switch> ) } 

    每當路由改變時,這將使React-Router呈現一個新的路由組件。 顯然,這有超過#1的性能問題。

與此無關,請在Notification.js 這一行上添加key={i}來解決可怕Each child in an array or iterator should have a unique "key" prop. 警告。

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM