redux 异步action

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(...);
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容