redux-thunk中文
发布时间:2020-12-15 07:26:42 所属栏目:百科 来源:网络整理
导读:thunk是redux解决异步的中间件。 我们为什么要使用redux-thunk这个中间件呢? 如果你不确定是否需要使用,那就不要用了(redux也是这个原则) 为啥会有redux-thunk这个东西呢 redux-thunk中间件可以允许你写的action creator函数可以返回action对象的同时,
thunk是redux解决异步的中间件。 我们为什么要使用redux-thunk这个中间件呢?如果你不确定是否需要使用,那就不要用了(redux也是这个原则) 为啥会有redux-thunk这个东西呢redux-thunk中间件可以允许你写的action creator函数可以返回action对象的同时,也可以返回一个函数。这个中间件可以被用来延缓分发action的时机,或者实现只在满足某个条件的时候才触发action。内部函数以dispatch和getState作为参数。 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) ); 实例todo~~ 资源推荐阮一峰 redux中间件与异步操作 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |