1、安装redux-thunk
npm install redux-thunk
npm install redux-thunk
2、redux/store.js
引入redux-thunk
/*
该文件专门用于创建一个为Count组件服务的store对象
*/
//引入createStore,专门创建redux中最为核心的store对象
import {createStore,applyMiddleware} from 'redux'
//引入cunter.redux.js文件
import countReducer from './count_reducer'
//引入redux-thunk用于支持异步action
import {thunk} from 'redux-thunk'
//暴露store
export default createStore(countReducer,applyMiddleware(thunk))
3、redux/count_action.js
/*
该文件专门为Count组件生成action对象
*/
import {INCREMENT,DECREMENT} from './constant'
import store from "./store";
// function createIncrementAction(data){
// return {type:'increment',data}
// }
export const createIncrementAction = data=>({type:INCREMENT,data})
// function createDecrementAction(data){
// return {type:'decrement',data}
// }
//同步action,就是形参为data,返回值为action对象
export const createDecrementAction = data=>({type:DECREMENT,data})
// export default {
// createIncrementAction,
// createDecrementAction
// }
//所谓的异步action,就是指action的值为函数,异步action中一般都会调用同步action,异步action不是必须要用的
export const createIncrementAsyncAction = (data,time)=>{
return ()=>{
setTimeout(()=>{
//通知redux
store.dispatch(createIncrementAction(data))
},time)
}
}
4、调用
import React, {Component} from "react";
//引入store,用于获取数据
import store from '../../redux/store'
//引入actionCreator 专门创建action对象
import {createDecrementAction,createIncrementAction,createIncrementAsyncAction} from '../../redux/count_action'
export default class Count extends Component {
state = {
count:store.getState()
}
componentDidMount() {
//监测redux中的数据的变化,只要改变,就会调用render
store.subscribe(()=>{
this.setState({
count:store.getState()
})
})
}
//加法
increment=()=>{
const {value} = this.selectNum
//通知redux 改变
// store.dispatch({type:'increment',data:parseInt(value)})
store.dispatch(createIncrementAction(parseInt(value)))
}
//减法
decrement=()=>{
const {value} = this.selectNum
store.dispatch(createDecrementAction(parseInt(value)))
}
//奇数加
incrementIfOdd=()=>{
const {value} = this.selectNum
const {count} = this.state
if(count%2!==0)
{
store.dispatch(createIncrementAction(parseInt(value)))
}
}
//异步加
incrementAsync=()=>{
const {value} = this.selectNum
// setTimeout(()=>{
store.dispatch(createIncrementAsyncAction(parseInt(value),500))
// },500)
}
render()
{
return(
<div>
<h1>当前求和为:{store.getState()}</h1>
<select ref={(c)=>this.selectNum=c}>
<option value="1">1</option>
<option value="2">2</option>
<option value='3'>3</option>
</select>
<button onClick={this.increment}>+</button>
<button onClick={this.decrement}>-</button>
<button onClick={this.incrementIfOdd}>当前求和为奇数在加</button>
<button onClick={this.incrementAsync}>异步加</button>
</div>
);
}
}