题目重现
当同时运用二者时,在代码中切换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。