redux使用redux-thunk中间件处理异步状态管理请求
redux处理异步状态管理请求
npm i redux-thunk -S
import {createStore,applyMiddleware,combineReducers,compose} from "redux"
import thunk from "redux-thunk" //中间件,用来处理异步请求
//const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose
//let store =createStore(rootReducer,composeEnhancers(applyMiddleware(thunk)))
let store =createStore(reducer,state,applyMiddleware(thunk))
//let store =createStore(reducer,state)
export default store
<button onClick={()=>{
store.dispatch(actionLogin({username:'xxx',password:'xxxx'}))
.then(
res=>console.log('组件收到的回执',res)
)
}}>login</button>
actionCreators
export const actionLogin =({username,password}) =>{
return (dispach) =>{
return request.get("/mock",{data:{username,password}})
.then(
res=>{
dispach({type:"LOGIN",payload:res})
return res //非必须,可以不用发送回执
}
)
}
}
reducers
let initState ={} const login =(state=initState,{type,payload}) =>{ console.log("reducer",state,type) switch (type) { case "LOGIN": / /... copy + 更新 + 返回 return state + payload default : return state; } } export default login

浙公网安备 33010602011771号