【问题标题】:I'm getting error after upgrading to Material UI 4 - withStyles升级到 Material UI 4 后出现错误 - withStyles
【发布时间】:2019-06-04 17:35:43
【问题描述】:

从 v3.9.x 升级到 MUI v4.0.2 后出现以下错误:

您必须将组件传递给 connect 返回的函数。而是收到 {"propTypes":{},"displayName":"WithStyles(MyComponent)","options":{"defaultTheme":{"breakpoints":{"keys":["xs","sm"," md","lg","xl"],"值": ...

我的组件:

import { withStyles } from '@material-ui/core/styles'

const getStyles = theme => ({
  fooBar: {
    ...
  },
})

...
export default withStyles(getStyles)(MyComponent)

我的容器:

import { connect } from 'react-redux'
import MyComponent from './MyComponent'
...
export default connect(mapStateToProps, mapDispatchToProps)(MyComponent)

如何迁移withStyles

【问题讨论】:

  • 你使用的是什么版本的 react-redux?我认为这与github.com/reduxjs/react-redux/issues/914 有关,如果您使用的是 react-redux 6 或 7 版,我认为应该修复。
  • @RyanCogswell 这已经解决了这个问题!将react-redux 从 5.x 升级到 7.0 后,问题就消失了!请写一个答案,以便我可以接受它,未来的人会立即知道解决方案。 ??????

标签: reactjs migration material-ui


【解决方案1】:

5.0.7 及更早版本的 react-redux 对传递给 connect 的组件执行了以下验证:

https://github.com/reduxjs/react-redux/blob/v5.0.7/src/components/connectAdvanced.js#L91

    invariant(
      typeof WrappedComponent == 'function',
      `You must pass a component to the function returned by ` +
      `${methodName}. Instead received ${JSON.stringify(WrappedComponent)}`
    )

随着React.forwardRef(在 Material-UI v4 中大量使用)和 React 16.8 中引入的其他功能(钩子)的引入,可以有一个 not 的组件类型一个函数。

react-redux 的更新版本使用 isValidElementType 来自 react-is 包。这样可以正确识别forwardRef等方法返回的组件类型。

我相信 react-redux 5.1 及更高版本应该都能正常工作,而不会错误地导致问题中提到的错误。

【讨论】:

    【解决方案2】:

    这就是我的做法:

    import { withStyles } from '@material-ui/core/styles';

    定义您的样式对象:查看 material-ui 示例以获得指导

    const styles => ({
      root: {
        display: 'flex',
      }
    });
    

    然后使用您的样式导出组件:

    export default withStyles(styles)(YourComponent);
    

    【讨论】:

    • 它在升级到 v4 之前工作。 有什么区别?另外,您的 const styles => ... 语法看起来无效。
    • 您的代码似乎已更改。我使用容器来连接我的组件。也许这就是问题所在?
    • 我已经添加了函数getStyles以避免混淆。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-07
    • 2020-01-19
    • 2014-10-06
    • 1970-01-01
    • 2021-09-26
    • 2011-06-23
    相关资源
    最近更新 更多