美文网首页
redux 异步action

redux 异步action

作者: 书简_yu | 来源:发表于2019-05-04 17:19 被阅读0次

    redux 异步action

    yarn add redux-thunk

    import thunkMiddleware from 'redux-thunk';
    import { createStore, applyMiddleware } from 'redux';
    import reducer form './reducer';
    
    function reudcer(state=0, action){
        // ...
    }
    
    let store = createStore(
        reducer,
        applyMiddleware(thunkMiddleware)
    )
    
    function incrementAsync() {
        return dispatch => {
            setTimeout(() => { 
                // dispath一个action
                dispatch({type: 'ADD'});
            }, 1000);
        };
    }
    
    // dispatch上面那个异步函数
    store.dispatch(incrementAsync());
    
    // 这就是一个简单的demo
    

    参考 Redux Thunk

    api请求demo

    function foo(){
        return function(dispatch){
            retrun axios('http://localhost:4000').then(
                data => dispatch({type: 'FERCH_DATA', data}),
                err => dispatch({type: 'FETCH_ERR', err}),
            )
        }
    }
    
    store.dispatch(foo());
    
    // 上述foo可用箭头函数改写,实现柯里化
    const foo = dispatch => axios('...').then(...);
    

    相关文章

      网友评论

          本文标题:redux 异步action

          本文链接:https://www.haomeiwen.com/subject/gccfoqtx.html