connect传mergeProps报Cannot read properties of undefined(reading 'root')
这个报错的核心触发点是上层withStyles注入的classes props丢失,组件渲染读取classes.root时拿到undefined,和你传入mergeProps强相关,按以下步骤排查修复:
首先修正
compose的错误写法compose要求所有入参必须是「接收组件、返回包装后组件」的高阶组件函数,你当前代码提前给connect传入MyComponent执行,相当于给compose传入了一个已包装完成的组件值而非函数,本身就不符合compose调用规范。先把基础写法调整正确:export default compose( withStyles(styles, { withTheme: true }), connect( mapStateToProps, mapDispatchToProps, mergeProps ) )(MyComponent)修复自定义
mergeProps的逻辑漏洞connect的mergeProps函数签名为(stateProps, dispatchProps, ownProps) => Object,不传该参数时react-redux会使用默认合并逻辑:{ ...ownProps, ...stateProps, ...dispatchProps },会自动透传所有上层HOC(也就是这里的withStyles)注入的props、父组件传入的props。
绝大多数人自定义mergeProps时会漏掉第三个参数ownProps,只合并前两个参数的内容,直接把classes、theme这类withStyles注入的核心props丢掉,直接触发你看到的读取'root'属性报错。
正确的mergeProps基础写法如下,必须保证透传ownProps:const mergeProps = (stateProps, dispatchProps, ownProps) => { return { ...ownProps, // 这一行漏写100%触发当前报错 ...stateProps, ...dispatchProps, // 此处追加你需要自定义合并的props逻辑即可 } }最终校验
写完后可以在mergeProps里打印ownProps.classes确认值存在,组件渲染时能正常拿到classes对象,报错就会消失。如果你的mergeProps有过滤props的逻辑,注意不要过滤掉classes、theme这类上层HOC注入的保留字段。
内容的提问来源于stack exchange,提问作者Ares

