connect和next的withRouter配合时刻时踩坑

题目重现

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

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

题目缘由

connect自身将组件变成pureComponent,next的withRouter并没有对router做任何处置惩罚,而是直接返回。

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}
  />
}

解决方案

1、将withRouter包在connect外层运用。

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

2、在运用connect时将组件pure的值默许改成false。

    原文作者:LynTss
    原文地址: https://segmentfault.com/a/1190000019322418
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞