文章来源于网络收集而来,版权归原创者所有,如有侵权请及时联系!
redux-promise 实例
import React, {Component} from 'react'
import {createStore, combineReducers, applyMiddleware} from 'redux';
import thunk from 'redux-thunk'
import redudxPromise from 'redux-promise';
import {composeWithDevTools} from 'redux-devtools-extension';
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);
});
}
},
MinusNumAsyncPromise(num) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(ActionCreators.MinusNum(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;
}
};
// 此处由于是开发阶段用了 redex 的开发工具所以不用考虑以下的变化。
const store = createStore(numReducer, composeWithDevTools(applyMiddleware(thunk, redudxPromise),
// other store enhancers if any
));
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))
.then(res => console.log(res))
.catch(e => console.log(e))
}}>
async+1
</button>
<button
onClick={() => {
store.dispatch(ActionCreators.MinusNum(1))
}}>
-1
</button>
<button
onClick={() => {
store.dispatch(ActionCreators.MinusNumAsyncPromise(1))
.then(res => console.log(res))
}}>
async Promise -1
</button>
</div>
)
}
}
export default Count
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论