redux-thunk中間件 中文翻譯
thunk是redux解决异步的中间件。
npm install --save redux-thunk
我们为什么要使用redux-thunk这个中间件呢?
如果你不确定是否需要使用,那就不要用了(redux也是这个原则)
为啥会有redux-thunk这个东西呢redux-thunk中间件可以允许你写的action creator函数可以返回action对象的同时,也可以返回一个函数。这个中间件可以被用来延缓分发action的时机,或者实现只在满足某个条件的时候才触发action。内部函数以dispatch和getState作为参数。
下面是一个action生产函数返回一个函数实现异步的dispatch:
const INCREMENT_COUNTER = 'INCREMENT_COUNTER';
function increment() {
return {
type: INCREMENT_COUNTER
};
}
function incrementAsync() {
return dispatch => {
setTimeout(() => {
// Yay! Can invoke sync or async actions with `dispatch`
dispatch(increment());
}, 1000);
};
}
下面是action生产函数返回一个函数实现按照条件决定是否分发action
function incrementIfOdd() {
return (dispatch, getState) => {
const { counter } = getState();
if (counter % 2 === 0) {
return;
}
dispatch(increment());
};
}
那么啥是thunk呢
thunk本质上是一个函数,它包裹一个表达式,使表达式的计算可以被推迟。
// calculation of 1 + 2 is immediate
// x === 3
let x = 1 + 2;
// calculation of 1 + 2 is delayed
// foo can be called later to perform the calculation
// foo is a thunk!
let foo = () => 1 + 2;
安装
npm install --save redux-thunk
为了使redux-thunk生效,我们需要调用applyMiddleware():
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers/index';
// Note: this API requires redux@>=3.1.0
const store = createStore(
rootReducer,
applyMiddleware(thunk)
);
实例
點(diǎn)擊查看更多內(nèi)容
為 TA 點(diǎn)贊
評論
評論
共同學(xué)習(xí),寫下你的評論
評論加載中...
作者其他優(yōu)質(zhì)文章
正在加載中
感謝您的支持,我會繼續(xù)努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進(jìn)行掃碼打賞哦