入到第四期,
代码大大简化,
但如果没有前面的演化过程,
一定让人蒙圈~~
三个主要文件:
index.js
import React from 'react'; import ReactDOM from 'react-dom'; import {Provider} from 'react-redux'; import './index.css'; import ControlPanel from './views/ControlPanel'; import store from './Store'; import registerServiceWorker from './registerServiceWorker'; ReactDOM.render( <Provider store={store}> <ControlPanel /> </Provider>,document.getElementById('root')); registerServiceWorker();
Counter.js
import React,{ Component } from 'react'; import PropTypes from 'prop-types'; import {connect} from 'react-redux'; import * as Actions from '../Actions.js'; const buttonStyle = { margin: '10px' }; const propTypes = { caption: PropTypes.string.isrequired }; function Counter({caption,onIncrement,onDecrement,value}){ return ( <div> <button style={buttonStyle} onClick={onIncrement}>+</button> <button style={buttonStyle} onClick={onDecrement}>-</button> <span> { caption } count: {value}</span> </div> ); } Counter.propTypes = { caption: PropTypes.string.isrequired,onIncrement: PropTypes.func.isrequired,onDecrement: PropTypes.func.isrequired,value: PropTypes.number.isrequired }; function mapStateToProps(state,ownProps) { return { value: state[ownProps.caption] } } function mapDispatchToProps(dispatch,ownProps) { return { onIncrement: () => { dispatch(Actions.increment(ownProps.caption)); },onDecrement: () => { dispatch(Actions.decrement(ownProps.caption)); } } } export default connect(mapStateToProps,mapDispatchToProps)(Counter);
Summary.js
import React,{Component} from 'react'; import PropTypes from 'prop-types'; import {connect} from 'react-redux'; function Summary ({value}) { return ( <div>Total Count: {value}</div> ); } Summary.propTypes = { value: PropTypes.number.isrequired }; function mapStateToProps(state){ let sum = 0; for (const key in state) { if (state.hasOwnProperty(key)) { sum += state[key]; } } return {value: sum}; } export default connect(mapStateToProps)(Summary);