instructions

  • The react beginners
  • Es6 beginner, have some understanding and use of decoration mode

Use of the React decorator

Look at the decoration mode

  • The Decorator pattern does not rely heavily on how objects are created, but rather focuses on extending their additional functionality. Instead of just relying on stereotype inheritance, we used a single base object and gradually added Decorator objects that provided additional functionality. The idea is to add properties or methods to base objects rather than subclassing them, so it’s lean.

React uses a decorator to write connect in Redux

  • Normally we need a Reducer and an action to wrap your Component.
  • Let’s say you already have a reducer with a key of main and an action.js. Our app.js will write like this:
import React from 'react'
import {render} from 'react-dom'
import {connect} from 'react-redux'
import {bindActionCreators} from 'redux'
import action from 'action.js'

class App extends React.Component{
  render(){
    return <div>hello</div>}}function mapStateToProps(state){
  return state.main
}
function mapDispatchToProps(dispatch){
  return bindActionCreators(action,dispatch)
}
export default connect(mapStateToProps,mapDispatchToProps)(App)
Copy the code
  • Use the decorator @
import React from 'react'
import {render} from 'react-dom'
import {connect} from 'react-redux'
import {bindActionCreators} from 'redux'
import action from 'action.js'

@connect(
 state= >state.main,
 dispatch=>bindActionCreators(action,dispatch)
)
class App extends React.Component{
  render(){
    return <div>hello</div>}}Copy the code

Reasonably compressed code

Of course, we need to use action and reducer every time, we have to write so much, and then we extract the connect

import {connect} from 'react-redux'
import {bindActionCreators} from 'redux'
import action from 'action.js'

export default connect(
 state= >state.main,
 dispatch=>bindActionCreators(action,dispatch)
)
Copy the code
  • We use this in components
import React from 'react'
import {render} from 'react-dom'
import connect from 'connect.js'

@connect
export default class App extends React.Component{
  render(){
    return <div>hello</div>
  }
}

Copy the code

Configure the decorators

  • Note that the decorator is used here, you need to install the module babel-plugin-transform-decorators-legacy and configure it in Babel:
{
  "plugins": ["transform-decorators-legacy"]}Copy the code

If you are using vscode, you can add the jsconfig.json file to the project root directory to remove the code warning:

{
  "compilerOptions": {
    "experimentalDecorators": true}}Copy the code

Practical article

  • Now that we understand the decorator, let’s start writing one
  • React writes a decorator that preloads data