Redux计数器

功能:计数器组件,每点击按钮,显示数字加1
组件:
****1. UI组件:又称"纯组件",由参数决定它的值。****
只负责 UI 的呈现,不带有任何业务逻辑。
没有状态(即不使用this.state这个变量)。
所有数据都由参数(this.props)提供。
不使用任何 Redux 的 API。
****2.容器组件:负责管理数据和逻辑****
负责管理数据和业务逻辑,不负责 UI 的呈现
带有内部状态
使用 Redux 的 API
主要函数:
connect: 将这两种组件连起来。以下是两种组件。
(1) 输入逻辑:外部的数据(即state对象)如何转换为 UI 组件的参数
(2) 输出逻辑:用户发出的动作如何变为 Action 对象,从 UI 组件传出去。
provide组件: 可以让容器组件拿到state对象(外部的数据),才能生成 UI 组件的参数。这样provider包含的所有子组件就默认都可以拿到state了。

import React, { Component, PropTypes } from 'react'
import ReactDOM from 'react-dom'
import { createStore } from 'redux'
import { Provider, connect } from 'react-redux'

// React component
class Counter extends Component {
  render() {
    //定义里面的两个函数value,onIncreaseClick
    const { value, onIncreaseClick } = this.props
    return (
    <div>
      //UI组件
      <span>{value}</span>
      //容器组件
      <button onClick={onIncreaseClick}>Increase</button>
    </div>
    )
  }
}
//counter中函数内的属性设置
Counter.propTypes = {
  value: PropTypes.number.isRequired,
  onIncreaseClick: PropTypes.func.isRequired
}

// Action
const increaseAction = { type: 'increase' }

// Reducer
function counter(state = { count: 0 }, action) {
  const count = state.count
  switch (action.type) {
    case 'increase':
      return { count: count + 1 }
    default:
      return state
   }
}

// Store
const store = createStore(counter)

// Map Redux state to component props
//value到state的映射 
function mapStateToProps(state) {
  return {
    value: state.count
  }
}
// Map Redux actions to component props
//onIncreaseClick到dispatch的映射
function mapDispatchToProps(dispatch) {
  return {
    onIncreaseClick: () => dispatch(increaseAction)
  }
}

// Connected Component
//将这输入逻辑与输出逻辑组件连接起来
const App = connect(
   mapStateToProps,
   mapDispatchToProps
)(Counter)

ReactDOM.render(
   <Provider store={store}>
     <App />
   </Provider>,
   document.getElementById('root')
)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、什么情况需要redux? 1、用户的使用方式复杂 2、不同身份的用户有不同的使用方式(比如普通用户和管...
    初晨的笔记阅读 2,066评论 0 11
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,638评论 25 708
  • 前言 本文 有配套视频,可以酌情观看。 文中内容因各人理解不同,可能会有所偏差,欢迎朋友们联系我讨论。 文中所有内...
    珍此良辰阅读 11,948评论 23 111
  • 学习必备要点: 首先弄明白,Redux在使用React开发应用时,起到什么作用——状态集中管理 弄清楚Redux是...
    贺贺v5阅读 8,957评论 10 58
  • 今天要写写舅舅家二表姐的故事。 二姐在家里排行老二,上面有大姐,下面有两个弟弟,一个妹妹。小时候没什么可说的,正常...
    麦子2008阅读 331评论 11 8