Created
August 18, 2016 22:43
-
-
Save Hilaryous/94e7315d40fbe62402c073e07c019f37 to your computer and use it in GitHub Desktop.
Smart and Dumb Component interaction example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//SMART COMPONENT | |
import React, { Component, PropTypes } from 'react'; | |
import { connect } from 'react-redux'; | |
import { bindActionCreators } from 'redux'; | |
import * as actionCreators from './actions'; | |
import DumbComponent from './DumbComponent'; | |
class SmartComponent extends Component { | |
static propTypes = { | |
params: PropTypes.object, | |
myInfo: PropTypes.object, | |
dispatch: PropTypes.func, | |
fetchMyInfo: PropTypes.func, | |
showInfo: PropTypes.bool, | |
toggleMyInfo: PropTypes.func, | |
}; | |
componentWillMount() { | |
if (this.props.params) { | |
this.props.fetchMyInfo(this.props.params); | |
} | |
} | |
changeMyInfo = () => { | |
this.props.toggleMyInfo(!this.props.showInfo); | |
} | |
render() { | |
return ( | |
<div className="clearfix"> | |
<DumbComponent | |
myInfo={myInfo} | |
changeMyInfo={this.changeMyInfo} | |
/> | |
</div> | |
); | |
} | |
} | |
function mapStateToProps(state) { | |
return { | |
myInfo: state.myInfo, | |
}; | |
} | |
function mapDispatchToProps(dispatch) { | |
return bindActionCreators(actionCreators, dispatch); | |
} | |
export default connect(mapStateToProps, mapDispatchToProps)(SmartComponent); | |
// DUMB COMPONENT | |
//SMART COMPONENT | |
import React, { Component, PropTypes } from 'react'; | |
class SmartComponent extends Component { | |
static propTypes = { | |
myInfo: PropTypes.object, | |
toggleMyInfo: PropTypes.func, | |
}; | |
render() { | |
return ( | |
<div className="clearfix"> | |
<button onClick={this.props.toggleMyInfo}>Show/Hide Info </button> | |
{this.props.myInfo} | |
</div> | |
); | |
} | |
} | |
//actions | |
export function toggleMyInfo(showInfo) { | |
return { | |
type: 'TOGGLE_MY_INFO', | |
showInfo, | |
}; | |
} | |
export function fetchMyInfo(params) { | |
fetch(url/to/getmyinfo) | |
.then(() => { | |
return { | |
type: 'FETCH_MY_INFO', | |
myInfo, | |
}; | |
}) | |
} | |
//reducers | |
export default function myInfo(state = initialState, action) { | |
switch (action.type) { | |
case 'FETCH_MY_INFO': | |
return { | |
...state, | |
myInfo: action.myInfo, | |
}; | |
case 'TOGGLE_MY_INFO': | |
return { | |
...state, | |
showInfo: action.showInfo, | |
}; | |
default: | |
return state; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment