文章来源于网络收集而来,版权归原创者所有,如有侵权请及时联系!
redux-thunk 中间件
redux-thunk
中间件改造了 redux 的 dispatch 方法允许我们用 store.dispatch(fn)
, fn
可以是一个函数。而且此函数可以接受两个参数: dispatch
、 getState
做为参数。
安装
npm install redux-thunk
配置中间件
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import reducer from './reducers';
// Note: this API requires redux@>=3.1.0
const store = createStore(
reducer,
applyMiddleware(thunk)
);
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);
};
}
store.dispatch(incrementAsync());
redux-thunk 中间件的返回值的处理
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import reducer from './reducers';
// Note: this API requires redux@>=3.1.0
const store = createStore(
reducer,
applyMiddleware(thunk)
);
// 异步删除的方法
function asyncDelStu(stuId) {
return (dispatch, getState) => {
return axios
.post('http://yapi.demo.qunar.com/mock/7378/api/delstu')
.then(res => {
// getState
dispatch(delStu(stuId));
})
.catch((res) => {
console.log(res);
});
}
}
store
.dispatch(asyncDelStu(33)) // 执行完成 dispatch 后,如果内部有返回值,此处还可以拿到返回值的结果。
.then(res => {
console.log(res.data)
})
.catch(e => {})
案例
import React, {Component} from 'react'
import {createStore, applyMiddleware} from 'redux';
import thunk from 'redux-thunk'
const ActionTypes = {
ADD_NUM: 'ADD_NUM',
MINUSE_NUM: 'MINUSE_NUM',
INIT_NUM: 'INIT_NUM'
};
const ActionCreators = {
AddNum(num) {
return {type: ActionTypes.ADD_NUM, payload: num}
},
MinusNum(num) {
return {type: ActionTypes.MINUSE_NUM, payload: num}
},
AddNumAsync(num) { // ** 核心: 添加异步增加的方法
return (dispatch, getState) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
dispatch(ActionCreators.AddNum(num));
resolve(num);
}, 1000);
});
}
}
}
const numReducer = (state = 0, action) => {
switch (action.type) {
case ActionTypes.ADD_NUM:
return state + action.payload;
case ActionTypes.MINUSE_NUM:
return state - action.payload
default:
return state;
}
};
const store = createStore(numReducer,applyMiddleware(thunk));
class Count extends Component {
constructor(props, context) {
super(props, context)
this.state = {
Num: 0
}
}
componentDidMount() {
store.subscribe(() => {
this.setState({
Num: store.getState()
})
});
}
render() {
return (
<div>
<p>{store.getState()}</p>
<p>{this.state.Num}</p>
<button
onClick={() => {
store.dispatch(ActionCreators.AddNum(1))
}}>
+1
</button>
<button
onClick={() => {
store
.dispatch(ActionCreators.AddNumAsync(2)) // dispatch 一个函数
.then(res => console.log(res))
.catch(e => console.log(e))
}}>
async+1
</button>
<button
onClick={() => {
store.dispatch(ActionCreators.MinusNum(1))
}}>
-1
</button>
</div>
)
}
}
export default Count
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论