实操《深入浅出React和Redux》第四期--react-redux
发布时间:2020-12-15 06:38:54 所属栏目:百科 来源:网络整理
导读:入到第四期, 代码大大简化, 但如果没有前面的演化过程, 一定让人蒙圈~~ 三个主要文件: index.js import React from 'react';import ReactDOM from 'react-dom';import {Provider} from 'react-redux';import './index.css';import ControlPanel from './
入到第四期, 代码大大简化, 但如果没有前面的演化过程, 一定让人蒙圈~~ 三个主要文件: 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();
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);
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); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |