Basic React-Redux App
by Allie Yu
HTML
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/[email protected]/dist/redux.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-redux/5.0.5/react-redux.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
Babel + JSX
const { Provider, connect } = ReactRedux;
// Actions
const inc = () => ({ type: 'INC' });
const dec = () => ({ type: 'DEC' });
const initialState = {
count: 0,
};
const reducer = (state = initialState, action) => {
switch(action.type) {
case 'INC':
return Object.assign({}, state, { count: state.count + 1 });
case 'DEC':
return Object.assign({}, state, { count: state.count - 1 });
}
return state;
}
const store = Redux.createStore(reducer);
// mapStateToProps
const mapCount = state => ({ count: state.count });
// connected component
const Counter = connect(mapCount, { inc, dec })(props => (
<div>Count: {props.count} <button onClick={props.inc} >+</button> <button onClick={props.dec}>-</button></div>
));
ReactDOM.render(
<Provider store={store}>
<Counter />
</Provider>,
document.getElementById('container')
);