React + Redux实现计算案例

react实现常规的求和

export default class Count extends Component {
  state = {
    count: 0
  }
  increment = () => {
    // console.log(this.sele.value)
    let { value } = this.sele
    let { count } = this.state;
    this.setState({
      count: count + value * 1
    })
  }
  delement = () => {
    let { value } = this.sele;
    let { count } = this.state;
    this.setState({
      count: count - value * 1
    })
  }
  oddCount = () => {
    let { value } = this.sele
    let { count } = this.state
    if ( count % 2 !== 0) {
      this.setState({
        count: count + value * 1
      })
    }
  }
  asncAddMent = () => {
    let { value } = this.sele
    let { count } = this.state
    if ( count % 2 === 0) {
      setTimeout(() => {
        this.setState({
          count: count + value * 1
        })
      }, 500)
    }
  }
  render () {
    let { count } = this.state
    return (
      <div className="CountName">
        <div>求和: { count }</div>
        <select ref={(c) => this.sele = c}>
          <option>1</option>
          <option>2</option>
          <option>3</option>
        </select>
        <button onClick={this.increment}>+</button>
        <button onClick={this.delement}>-</button>
        <button onClick={this.oddCount}>奇数和加</button>
        <button onClick={ this.asncAddMent }>异步加</button>
      </div>
    )
  }
} 

redux实现的求和案例

在项目的根目录redux这个文件夹
store.js
count_rducer.js
count_actions.js
constant.js
这几个文件

store.js中的写法

// 引入CreaStore, 专门创建redux中最为核心的Store对象
import { createStore } from 'redux'
// 引入CountReducer服务的reducer
import CountReducer from './count_reducer'
// 暴露Store
export default createStore(CountReducer)

count_reducer.js


```/*
 1. 创建该文件的目的是为了服务reducer, reducer的本质就是一个函数
 2. reducer会接收两个参数, 分别为之前的状态: (preState),动作对象
 action 
*/
import {
  INCREMENT,
  DECREMENT
} from './constant'
const defaultState = 0;
export default function count_reducer(preState = defaultState, action) {
  // 从action中对象中获取 type data
  const { type, data } = action
  // 根据type决定如何加上数据
  switch (type) {
    case INCREMENT: // 如果是加的话
     return preState + data
     case DECREMENT: // 如果是减的话
      return preState - data
      default:
        return preState
  }
}

``count_actions


```// 该文件生成action
import {
  INCREMENT,
  DECREMENT
} from './constant'
export const createIncrement = data => ({type: INCREMENT, data})
export const createDelCrement = data => ({ type: DECREMENT, data})

constant.js

export const INCREMENT = 'increment'
export const DECREMENT = 'decrement'

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值