How can I use decorators in a React Redux application?

后端 未结 2 848
感动是毒
感动是毒 2021-02-08 13:11

I’m creating simple application using React Redux. I want to use decorator to inject some methods in my component.. I saw similar code in other projects:

import          


        
相关标签:
2条回答
  • 2021-02-08 13:27

    Please note that we do not recommend using decorators for connecting components. You won’t find them anywhere in the official docs or examples.

    Just because some community examples use them doesn’t mean it’s a good idea: the spec is still changing, the tooling support is flaky, and frankly, you don’t need decorators for connect() because they desugar to simple function calls.

    For example, rather than

    @connect(mapStateToProps)
    class MyComponent extends Component {}
    

    you should write

    class MyComponent extends Component {}
    MyComponent = connect(mapStateToProps)(MyComponent)
    

    This way you won’t have to worry about them breaking until the proposal is part of the language.

    I recommend you to stick to the conventions we use in the official Redux examples and be very cautious about adopting experimental syntax extensions.

    0 讨论(0)
  • 2021-02-08 13:49

    Babel 6 doesn't support decorators with the es2015 preset, nor with the stage-0 preset. You'll have to add the babel-plugin-transform-decorators-legacy plugin to enable decorators:

    $ npm install --save-dev babel-plugin-transform-decorators-legacy
    

    And add to your plugins in .babelrc:

    {
      "plugins": [
        "transform-decorators-legacy",
        ...
      ]
    }
    

    This is the easiest way I know of to get decorator support. They're not included in babel by default as they haven't actually been standardized yet.

    0 讨论(0)
提交回复
热议问题