• 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
  • 相关阅读:
    创建对象的七种方式
    设计模式之工厂模式
    设计模式之单例模式
    排序算法之插入排序
    排序算法之选择排序
    类及对象初体验
    排序算法之冒泡排序
    迭代器和生成器
    装饰器
    函数进阶
  • 原文地址:https://www.cnblogs.com/anin/p/13582415.html
Copyright © 2020-2023  润新知