React-redux将HOC作为类装饰器@connect

时间:2018-10-02 15:16:05

标签: javascript reactjs redux ecmascript-next

我有一个使用ES+ proposed decorator syntax形式的react-redux的connect 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}}]}

我正在将Webpack 4与babel-loader一起使用。我的.babelrc文件是:

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

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

如何使@connect装饰器起作用?

1 个答案:

答案 0 :(得分:1)

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

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

babel-plugin-proposal-decorators