Componentdidmount Example


Example 1: use effect like component did mount


useEffect(() => {
console.log('I am the new componentDidMount')
}, [])
// Don't forget the empty array at the end

Example 2: component did update arguments


componentDidUpdate(prevProps, prevState) {
// only update chart if the data has changed
if (prevProps.data !== this.props.data) {
this.chart = c3.load({
data: this.props.data
});
}
}

Example 3: react native class component constructor


import React from 'react';  
import { View, TextInput } from "react-native";

class App extends React.Component {
constructor(props){
super(props);
this.state = {
name: ""
}
this.handleChange = this.handleChange.bind(this);
}
handleChange(text){
this.setState({ name: text })
console.log(this.props);
}
render() {
return (
<View>
<TextInput
value={this.state.name}
onChangeText={(text) =>this.handleChange(text)}
/>
</View>
}
}
export default App;

Example 4: componentDidUpdate


componentDidUpdate(prevProps, prevState) {
if (prevState.pokemons !== this.state.pokemons) {
console.log('pokemons state has changed.')
}
}

Example 5: react lifecycle example


class Test extends React.Component {
constructor() {
console.log('Constructor')
super();
this.state = {
count: 0
};
}

componentDidMount() {
console.log("component did mount");
}
componentDidUpdate() {
console.log("component did update");
}

onClick = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
console.log("render");
return (
<div>
Hello Test
<button onClick={this.onClick}>
{this.state.count}
</button>
</div>
);
}
}


//--for first time
//Constructor
//render
//component did mount
//--for any update
//render
//component did update

Example 6: lifecycle method react


INITIALIZATION= setup props and state 
MOUNTING= constructor->componentWillMount->render->componentDidMount//Birth
UPDATE= shouldComponentUpdate->componentWillUpdate->render
->componentDidUpdate //Growth
UNMOUNTING= componentWillUnmount //Death

Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable