文章来源于网络收集而来,版权归原创者所有,如有侵权请及时联系!
React-Redux 完整 demo
App.js 代码
import React, { Component } from 'react';
import RRDemo from './components/RRDemo';
class App extends Component {
render() {
return (
<div>
<RRDemo></RRDemo>
</div>
);
}
}
export default App;
index.js 代码
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import {Provider} from 'react-redux';
import store from './store';
ReactDOM.render(
<Provider store={store}>
<App></App>
</Provider>
, document.getElementById('root'));
store.js 代码
import {createStore, applyMiddleware} from 'redux';
import thunk from 'redux-thunk'
import redudxPromise from 'redux-promise';
import {composeWithDevTools} from 'redux-devtools-extension';
export const ActionTypes = {
ADD_NUM: 'ADD_NUM',
MINUSE_NUM: 'MINUSE_NUM',
INIT_NUM: 'INIT_NUM'
};
export 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;
}
};
// const store = createStore(numReducer, window.__REDUX_DEVTOOLS_EXTENSION__ &&
// window.__REDUX_DEVTOOLS_EXTENSION__());
const store = createStore(numReducer, composeWithDevTools(applyMiddleware(thunk, redudxPromise),
// other store enhancers if any
));
export default store;
组件代码:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { ActionCreators } from '../store';
function mapStateToProps(state) {
return {
Num: state
};
}
function mapDispatchToProps(dispatch) {
return {
AddNum: (num) => dispatch(ActionCreators.AddNum(num)),
MinusNum: (num) => dispatch(ActionCreators.MinusNum(num)),
AddNumAsync: (num) => dispatch(ActionCreators.AddNumAsync(num)),
MinusNumAsyn: (num) => dispatch(ActionCreators.MinusNumAsyncPromise(num))
};
}
class RRDemo extends Component {
render() {
return (
<div>
{ this.props.Num }
<hr/>
<button
onClick={ () => this.props.AddNum(1)}>
+1
</button>
<button
onClick={() => {
this.props.AddNumAsync(2)
.then(res => console.log(res))
.catch(e => console.log(e))
}}>
async+1
</button>
<button
onClick={() => {
this.props.MinusNum(1)
}}>
-1
</button>
<button
onClick={() => {
this.props.MinusNumAsyn(1)
.then(res => console.log(res))
}}>
async Promise -1
</button>
</div>
);
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(RRDemo);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论