11import React , { Component } from 'react'
22import PropTypes from 'prop-types'
3+ import { connect } from './React-redux' ;
34
45class ThemeSwitch extends Component {
56static contextTypes = {
6- store :PropTypes . object
7+ themeColor :PropTypes . string ,
8+ onSwitchColor :PropTypes . func
79}
810
9- constructor ( ) {
10- super ( )
11- this . state = {
12- themeColor :''
11+ handleSwitchColor ( color ) {
12+ if ( this . props . onSwitchColor ) {
13+ this . props . onSwitchColor ( color )
1314}
1415}
1516
16- componentWillMount ( ) {
17- const { store} = this . context
18- this . _updateThemeColor ( )
19- store . subscribe ( ( ) => this . _updateThemeColor ( ) )
20- }
17+ // componentWillMount () {
18+ // const { store } = this.context
19+ // this._updateThemeColor()
20+ // store.subscribe(() => this._updateThemeColor())
21+ // }
2122
22- _updateThemeColor ( ) {
23- const {
24- store
25- } = this . context
26- const state = store . getState ( )
27- this . setState ( {
28- themeColor :state . themeColor
29- } )
30- }
23+ // _updateThemeColor () {
24+ // const {
25+ // store
26+ // } = this.context
27+ // const state = store.getState()
28+ // this.setState({
29+ // themeColor: state.themeColor
30+ // })
31+ // }
3132
32- handleSwitchColor ( color ) {
33- const {
34- store
35- } = this . context
36- store . dispatch ( {
37- type :'CHANGE_COLOR' ,
38- themeColor :color
39- } )
40- }
33+ // handleSwitchColor (color) {
34+ // const {
35+ // store
36+ // } = this.context
37+ // store.dispatch({
38+ // type: 'CHANGE_COLOR',
39+ // themeColor: color
40+ // })
41+ // }
4142
4243render ( ) {
4344return (
4445< div >
4546< button
46- style = { { color :this . state . themeColor } }
47+ style = { { color :this . props . themeColor } }
4748onClick = { this . handleSwitchColor . bind ( this , 'red' ) }
4849>
4950 Red
5051</ button >
5152< button
52- style = { { color :this . state . themeColor } }
53+ style = { { color :this . props . themeColor } }
5354onClick = { this . handleSwitchColor . bind ( this , 'blue' ) }
5455>
5556 Blue
@@ -59,4 +60,23 @@ class ThemeSwitch extends Component {
5960}
6061}
6162
63+ const mapStateToProps = state => {
64+ return {
65+ themeColor :state . themeColor
66+ }
67+ }
68+
69+ const mapDispatchToProps = dispatch => {
70+ return {
71+ onSwitchColor :color => {
72+ dispatch ( {
73+ type :'CHANGE_COLOR' ,
74+ themeColor :color
75+ } )
76+ }
77+ }
78+ }
79+
80+ ThemeSwitch = connect ( mapStateToProps , mapDispatchToProps ) ( ThemeSwitch )
81+
6282export default ThemeSwitch