【问题标题】:React-redux connect HOC as a class decorator, @connectReact-redux 将 HOC 连接为类装饰器,@connect
【发布时间】:2019-03-07 18:11:38
【问题描述】:

我有一个使用 ES+ proposed decorator syntax 形式的 react-redux 连接 HOC 包装的组件:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import RegisterForm from './register-form';
import { registerUser } from '../store/api/Auth/actions';

@connect(null, { registerUser: registerUser })
export default class RegisterPage extends Component {
  handleSubmit = values =>
    this.props.registerUser(values);

  render() {
    return (
      <div>
        <h1>Register Here</h1>
        <RegisterForm onSubmit={this.handleSubmit} />
      </div>
    );
  }
}

我收到一个错误:

Uncaught Error: You must pass a component to the function returned by connect. Instead received {"kind":"class","elements":[{"kind":"field","key":"handleSubmit","placement":"own","descriptor":{"configurable":true,"writable":true,"enumerable":false}},{"kind":"method","key":"render","placement":"prototype","descriptor":{"writable":true,"configurable":true,"enumerable":false}}]}

我正在使用带有 babel-loader 的 Webpack 4。我的 .babelrc 文件是:

{
  "presets": [
      "@babel/preset-env",
      "@babel/preset-react"
    ],
    "plugins": [
      "@babel/plugin-proposal-class-properties",
      ["@babel/plugin-proposal-decorators", { "decoratorsBeforeExport": true }]
    ]
}

在我看来,连接函数的目标对象是类,但连接函数正在接收该类的属性描述符。我知道 React 和 Redux 团队不鼓励装饰器。这是一个相关的 SO 问题:React-Redux @connect syntax error

如何让@connect 装饰器工作?

【问题讨论】:

  • 正如你所指出的,我们确实不鼓励使用一般的装饰器,特别是使用 connect 作为装饰器。装饰器语法和插件仍然不稳定并不断变化。
  • @markerikson 感谢您的回复。看到其他人在使用它,我很好奇我缺少什么才能让它工作。
  • 这是一个不断变化的景观。如果您如此执着于使用不受官方支持的东西,那么您需要加倍努力。你需要找到一个版本的 babel-plugin-transform-decorators (或 -legacy)可以使这个工作。您可能还需要找到可以在 that 生态系统中工作的其他 babel 插件的匹配版本。不过,追逐这个想法对科学有好处,祝你好运! :)

标签: javascript reactjs redux ecmascript-next


【解决方案1】:

确保在插件类属性之前注入装饰器插件

{
  "plugins": [
    "@babel/plugin-proposal-decorators",
    "@babel/plugin-proposal-class-properties"
  ]
}

babel-plugin-proposal-decorators

【讨论】:

  • 请添加有关链接资源的一些信息/描述/上下文
  • 我仍然将描述符作为装饰器函数的第一个也是唯一的参数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-05
  • 2018-04-02
  • 1970-01-01
  • 2019-04-30
  • 2019-04-06
  • 1970-01-01
  • 2017-04-13
相关资源
最近更新 更多