import React, { Component } from 'react';
import store from '../../redux/store.js';
import { createJiaAction, createJianAction } from '../../redux/count_action.js';
export default class Count extends Component {
state = { name: '邓紫棋' };
componentDidMount() {
store.subscribe(() => {
this.setState({});
});
}
jia = () => {
const { value } = this.sum;
{}
store.dispatch(createJiaAction(Number(value) ));
};
jian = () => {
const { value } = this.sum;
store.dispatch(createJianAction(Number(value) ));
};
jiShu = () => {
const { value } = this.sum;
const count = store.getState();
if (count % 2 !== 0) {
store.dispatch(createJiaAction(Number(value) ));
}
};
yiBu = () => {
const { value } = this.sum;
setTimeout(() => {
store.dispatch(createJiaAction(Number(value) ));
}, 500);
};
render() {
const { Counm } = this.state;
return (
<div>
{}
<h1>当前求和为:{store.getState()}</h1>
<select
ref={(a) => {
this.sum = a;
}}
>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button onClick={this.jia}>+</button>
<button onClick={this.jian}>-</button>
<button onClick={this.jiShu}>当前求和为奇数再加</button>
<button onClick={this.yiBu}>异步加</button>
</div>
);
}
}
constant.js
export const JIA ='jia'
export const JIAN ='jian'
count_action.js
import {JIA,JIAN} from './constant.js';
export const createJiaAction=(data)=>{
return {type:JIA,data}
}
export const createJianAction=(data)=>{
return {type:JIAN,data}
}
count_reducer.js
import { JIA, JIAN} from './constant.js';
export default function countReducer(preState, action) {
if (preState === undefined) preState = 100
const { type, data } = action
console.log(type, data)
switch (type) {
case JIA:
return preState + data
case JIAN:
return preState - data
default:
return preState
}
}
store.js
import {createStore} from 'redux'
import countReducer from './count_reducer'
export default createStore(countReducer)