redux异步action_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

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)