redux使用redux-thunk中介軟體處理非同步狀態管理請求
阿新 • • 發佈:2020-08-29
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