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'