connect和next的withRouter共同时候时踩坑

问题重现

当同时使用二者时,在代码中切换router并不会从新reRender组件,代码以下:javascript

export default connect((state: any) => {
  return {
    x: state.common.x,
  }
})(withRouter(Index))

问题缘由

connect自己将组件变为pureComponent,next的withRouter并无对router作任何处理,而是直接返回。java

connect 源码
return function connect(
  mapStateToProps,
  mapDispatchToProps,
  mergeProps,
  {
    pure = true,
    areStatesEqual = strictEqual,
    areOwnPropsEqual = shallowEqual,
    areStatePropsEqual = shallowEqual,
    areMergedPropsEqual = shallowEqual,
    ...extraOptions
  } = {}
) {}
withRouter源码
render() {
  return <ComposedComponent
    router={this.context.router}
    {...this.props as any}
  />
}

解决方案

一、将withRouter包在connect外层使用。this

export default withRouter(
  connect((state: any) => {
    return {
      x: state.common.x,
    }
  })(Index),
)

二、在使用connect时将组件pure的值默认改成false。spa

相关文章
相关标签/搜索