Skip to content

Instantly share code, notes, and snippets.

@yaminmhd
Created March 24, 2018 16:39
Show Gist options
  • Select an option

  • Save yaminmhd/349555f84dedc1ad2d604b2622754991 to your computer and use it in GitHub Desktop.

Select an option

Save yaminmhd/349555f84dedc1ad2d604b2622754991 to your computer and use it in GitHub Desktop.
React Lifecycle events
/*
We can break React's life cycle methods into two categories
1. When a component gets mounted to the DOM and unmounted
2. When a component receives new data
When a component is initialized and added to the DOM (mounting) and when the component is removed from the DOM(unmounting).
These methods will be invoked only once during the life of the component
*/
//Some tasks that are important to do when a component mounts or unmounts
// - Establish some default props in our component
// - Set some initial state in our component
class Login extends React.Component {
constructor (props) {
super(props)
this.state = {
email: '',
password: ''
}
}
render () {
...
}
}
// a constructor to set an email and password property on our state object in our Login component
//To update the set, we call this.setState passing in an function which returns an object which overwrites one or both of the email and password properties
// - Make AJAX request to fetch some data needed for this component
class FriendsList extends React.Component {
componentDidMount () {
return axios.get(this.props.url).then(this.props.callback)
}
render () {
...
}
}
//componentDidMount is called directly after the component is mounted to the DOM
// - Set up and remove listeners
class FriendsList extends React.Component {
componentDidMount () {
ref.on('value', function (snapshot) {
this.setState(function () {
return {
friends: snapshot.val()
}
})
}.bind(this)
}
render () {
...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment