React.js 01 _ 입문.
1) React.js 생명주기
★ 중요한 건 setState 는 render() function을 Call한다 ★
import React,{useState} from 'react';
class App extends React.Component {
constructor(props){
super(props);
console.log("hello");
this.state = {
count:1,
};
this.add = () => {
this.setState(current => ({ count: current.count + 1 }));
};
this.minus = () => {
this.setState(current => ({ count: current.count - 1 }));
};
}
componentDidMount() {
console.log("Component rendered");
}
componentDidUpdate() {
console.log("I just updated");
}
componentWillUnmount() {
console.log("Goodbye, cruel world");
}
render(){
console.log("I'm rendering");
return (
<div>
<h1>The number is : {this.state.count}</h1>
<button onClick={this.add}>Add</button>
<button onClick={this.minus}>Minus</button>
</div>
);
}
}
export default App;
이를 활용한 비동기함수 처리
import React,{useState} from 'react';
// fetch !
class App extends React.Component {
constructor(props){
super(props);
this.state = {
isLoading : true
};
}
componentDidMount() {
setTimeout(() => {
this.setState({isLoading: false});
},3000);
}
render(){
const {isLoading} = this.state;
return (
<div>{isLoading ? "Loading..." : "We are ready"}</div>
);
}
}
export default App;
댓글남기기