Lifecycle trong component
Mỗi thành phần trong React có vòng đời mà bạn có thể theo dõi và thao tác ứng với ba giai đoạn chính đó là Mounting, Updating, and Unmounting.

Mounting : được hiểu là những component đã được nhúng vào DOM hiển thị trên UI
Updating : trong quá trình hiển thị mà component có thể thay đổi trạng thái thì sẽ qua bước Updating
Unmounting : là quá trình loại component ra khỏi DOM , hay component đó được loại bỏ ra khỏi UI
Ta có thể thấy rõ componentDidMount và componentWillUnmount đều thực hiện duy nhất 1 lần trong 3 giai đoạn chính

Ví dụ về componentDidMount
componentDidMount được thực hiện sau quá trình render và nó chỉ được kích hoạt 1 lần duy nhất
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
componentDidMount() {
setTimeout(() => {
this.setState({favoritecolor: "yellow"})
}, 1000)
}
render() {
return (
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
);
}
}
ReactDOM.render(<Header />, document.getElementById('root'));
Ví dụ về componentWillUnmount
componentWillUnmount là một phương thức được gọi khi một component bị remove khỏi DOM
class Container extends React.Component {
constructor(props) {
super(props);
this.state = {show: true};
}
delHeader = () => {
this.setState({show: false});
}
render() {
let myheader;
if (this.state.show) {
myheader = <Child />;
};
return (
<div>
{myheader}
<button type="button" onClick={this.delHeader}>Delete Header</button>
</div>
);
}
}
class Child extends React.Component {
componentWillUnmount() {
alert("The component named Header is about to be unmounted.");
}
render() {
return (
<h1>Hello World!</h1>
);
}
}
ReactDOM.render(<Container />, document.getElementById('root'));
Ta có thể thấy lúc đầu trong DOM được dựng bởi component Container có một component con là Child nhưng khi show sang trạng thái false thì Child bị loại khỏi DOM của Component Container do đó componentWillUnmount() được gọi từ component Child
Last updated
Was this helpful?