使用react实现 计数器的代码
参考阮一峰大神redux地址
import { createStore, applyMiddleware } from 'redux';
import { Provider, connect } from 'react-redux';
import thunkMiddleware from 'redux-thunk';
// action type
const INCREASE_COUNT = 'INCREASE_COUNT';
const DECREASE_COUNT = 'DECREASE_COUNT';
// action creator
const increaseCount = () => ({
type: INCREASE_COUNT
});
const decreaseCount = () => ({
type: DECREASE_COUNT
});
const increaseCountAsync = () => dispatch => {
setTimeout(() => {
dispatch(increaseCount());
}, 1000);
};
// reducer
const reducer = (state = 0, action) => {
switch (action.type) {
case INCREASE_COUNT: return ++state;
case DECREASE_COUNT: return --state;
default: return state;
}
};
// store
const store = createStore(reducer, applyMiddleware(thunkMiddleware));
// view
const Counter = ({ count, dispatch }) => (
<div>
<button onClick={() => dispatch(increaseCount())}>+</button>
<button onClick={() => dispatch(decreaseCount())}>-</button>
<button onClick={() => dispatch(increaseCountAsync())}>Increase Async</button>
<div>{count}</div>
</div>
);
// container
const mapStateToProps = state => ({ count: state });
const CounterContainer = connect(mapStateToProps)(Counter);
// connect to store
const App = (
<Provider store={store}>
<CounterContainer />
</Provider>
);
ReactDOM.render(App, mountNode);