React Router 4.x - PrivateRoute not working after connecting to Redux

不打扰是莪最后的温柔 提交于 2019-11-30 00:35:06
Tomasz Mularczyk

Complementary to @Tharaka answer you can pass {pure: false} to connect method as described in react-redux troubleshooting section.

React-redux makes shallow comparison of props in shouldComponentUpdate hook to avoid unnecessary re-renders. If context props changed (react-router) it doesn’t check for that and it assumes nothing has changed.

{ pure:false } simply disables this shallow comparison.

According to react-router documentation you may just wrap your connect function with withRouter:

// before
export default connect(mapStateToProps)(Something)

// after
import { withRouter } from 'react-router-dom'
export default withRouter(connect(mapStateToProps)(Something))

This worked for me.

This is known issue in react-redux and you can read more about this here. The problem is connect HoC have implemented shouldComponentUpdate, so that wrapped component doesn't rerender if props aren't changed. Since react-router use context to pass route changes, the wrapped component doesn't rerender when routes change. But it seems they are going to remove shouldComponentUpdate in 5.1 version of react-redux. Currently, as a workaround, I pass a prop coming from Router like this.props.match.params to connected child component even though I don't use it in inside. But it will make rerendering the component each time when routes change.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!