1

redux-装饰器模式

源码:https://github.com/wsdo/redux...
课程地址: https://segmentfault.com/ls/1...

babel 依赖,和配置

npm i @babel/plugin-proposal-decorators -S

  "babel": {
    "presets": [
      "react-app"
    ],
    "plugins":[
      [
        "@babel/plugin-proposal-decorators",
        {
          "legacy": true
        }
      
      ]
    ]
  },

语法糖{把state 和 action 挂在到 当前的组件props上}

第一个参数是 state 第二个参数是action

使用装饰器前:

 const actionCreators = {eat,hungry}
export default connect((state)=>{
  return {num: state.num,list:state.list}
},{eat,hungry,eatAsync,getArticle})(App)

使用装饰器后:

@connect(state => state, { eat, hungry, eatAsync, getArticle })

记得导出哦

export default App

App.js 源码

import React from 'react'
import logo from './logo.svg'
import './App.css'
import { eat, hungry, eatAsync, getArticle} from './stark.redux'
import { connect } from 'react-redux'


@connect(state => state, { eat, hungry, eatAsync, getArticle })

class App extends React.Component {
  render () {
    const {num, eat, hungry , eatAsync, getArticle, list} = this.props
    return (
      <div className='App'>
          {list.map((item,index)=>{
            return <div key={index}>
              {item.title}
            </div>
          })}
        <header className='App-header'>
          <img src={logo} className='App-logo' alt='logo' />
          <p>
            【redux完全指南】系列1:从入门到会用
            <br></br>
            hi gusy, I am stark
          </p>
          <div>装饰器模式</div>
          <a
            className='App-link'
            href='https://shudong.wang'
            target='_blank'
            rel='noopener noreferrer'>跟着stark wang 学redux</a>
          <h2>stark wang 当前的体重为{num}斤</h2>
          <button onClick={() => {eat()}}>
            吃了一坨山珍海味
          </button>
          <button onClick={() => {eatAsync()}}>
            等了一会,吃了一个煎饼
          </button>
          <button onClick={() => {hungry()}}>
            饿了一天
          </button>
          <button onClick={() => {getArticle()}}>
            获取文章
          </button>
        </header>
      </div>
    )
  }

}
// const mapStateToProps = (state)=>{
//   return {num:state}
// }

// const actionCreators = {eat,hungry}
// export default connect((state)=>{
//   return {num: state.num,list:state.list}
// },{eat,hungry,eatAsync,getArticle})(App)

export default App

2019-06-15-17-03-16


西树先森
7.1k 声望926 粉丝

从事开发多年,前端、后端(go、Python、php)、服务架构都有涉猎,经历过大公司、创业公司,擅长前端及公司技术选型。