|
| 1 | +<html> |
| 2 | + |
| 3 | +<body> |
| 4 | + <div id="root"></div> |
| 5 | + <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script> |
| 6 | + <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> |
| 7 | + <script type="text/javascript"> |
| 8 | + const e = React.createElement; |
| 9 | + |
| 10 | + const rootReducer = (state, action) => { |
| 11 | + switch (action.type) { |
| 12 | + case 'UP': |
| 13 | + return { |
| 14 | + counter: state.counter + 1 |
| 15 | + } |
| 16 | + case 'DOWN': |
| 17 | + return { |
| 18 | + counter: state.counter - 1 |
| 19 | + } |
| 20 | + default: |
| 21 | + return state; |
| 22 | + } |
| 23 | + }; |
| 24 | + |
| 25 | + |
| 26 | + class Store { |
| 27 | + constructor(initialState, reducer) { |
| 28 | + this.state = initialState; |
| 29 | + this.reducer = reducer; |
| 30 | + this.listeners = []; |
| 31 | + } |
| 32 | + |
| 33 | + dispatch(action) { |
| 34 | + this.state = this.reducer(this.state, action); |
| 35 | + this.listeners.forEach(listener => listener()); |
| 36 | + } |
| 37 | + |
| 38 | + subscribe(listener) { |
| 39 | + this.listeners.push(listener); |
| 40 | + } |
| 41 | + |
| 42 | + getState() { |
| 43 | + return this.state; |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + const store = new Store({ counter: 1 }, rootReducer); |
| 48 | + |
| 49 | + const connect = (mapStateToProps) => { |
| 50 | + return Component => { |
| 51 | + return class extends React.Component { |
| 52 | + constructor(props) { |
| 53 | + super(props); |
| 54 | + |
| 55 | + this.state = store.getState(); |
| 56 | + |
| 57 | + store.subscribe(() => { |
| 58 | + this.setState(store.getState()); |
| 59 | + }); |
| 60 | + } |
| 61 | + |
| 62 | + render() { |
| 63 | + return e(Component, mapStateToProps(store.getState())); |
| 64 | + } |
| 65 | + }; |
| 66 | + }; |
| 67 | + }; |
| 68 | + |
| 69 | + const mapStateToProps = (state) => { |
| 70 | + return { number: state.counter }; |
| 71 | + }; |
| 72 | + |
| 73 | + const Counter = connect(mapStateToProps)(props => { |
| 74 | + const up = e('button', { onClick: () => store.dispatch({ type: 'UP' }) }, 'UP'); |
| 75 | + const down = e('button', { onClick: () => store.dispatch({ type: 'DOWN' }) }, 'DOWN'); |
| 76 | + |
| 77 | + return e('div', {}, up, props.number, down); |
| 78 | + }); |
| 79 | + |
| 80 | + ReactDOM.render(e(Counter), document.getElementById('root')); |
| 81 | + </script> |
| 82 | +</body> |
| 83 | + |
| 84 | +</html> |
0 commit comments