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

相關文章
相關標籤/搜索