安装redux-thunk
redux-thunk
store中使用action
引入redux-thunk,用于支持异步action
从redux中引入中间件库applyMiddleware
修改createStore
的参数
// store.js
//引入createStore,专门用于创建redux中最为核心的store对象
import {createStore,applyMiddleware} from 'redux'
//引入为Count组件服务的reducer
import countReducer from './count_reducer'
//引入redux-thunk,用于支持异步action
import thunk from 'redux-thunk'
//导出store
export default createStore(countReducer,applyMiddleware(thunk))
异步action写法
export const createIncrementAsyncAction = (data,time) => {
return (dispatch)=>{
setTimeout(()=>{
dispatch(createIncrementAction(data))
},time)
}
}
组件中使用方法
//奇数再加
incrementIfOdd = ()=>{
const {value} = this.selectNumber
const count = store.getState()
if(count % 2 !== 0){
store.dispatch(createIncrementAction(value*1))
}
}