ReactJs에서 componentWillUnmount()를 올바르게 사용하는 방법
공식 튜토리얼에서:
componentWillUnmount()컴포넌트가 마운트 해제되어 파기되기 직전에 호출됩니다.타이머 비활성화, 네트워크 요청 취소, 에서 작성된 DOM 요소 청소 등 이 방법으로 필요한 청소를 수행합니다.componentDidMount
"무효 타이머"를 이해했습니다. fetch와 함께 중단될 수 있다AbortController그러나, 「DOM 요소를 소거한다」는 것은 이해할 수 없습니다.componentDidMount"그 경우의 예를 들면?
네트워크 요구 송신 라이브러리가 진행중인 네트워크 요구 콜의 중단을 서포트하고 있는 경우는, 에서 확실히 콜 할 수 있습니다.componentWillUnmount방법.
단, 청소에 관해서는DOM요소는 관심사입니다.저의 현재 경험을 바탕으로 몇 가지 예를 들어 보겠습니다.
첫 번째는...
import React, { Component } from 'react';
export default class SideMenu extends Component {
constructor(props) {
super(props);
this.state = {
};
this.openMenu = this.openMenu.bind(this);
this.closeMenu = this.closeMenu.bind(this);
}
componentDidMount() {
document.addEventListener("click", this.closeMenu);
}
componentWillUnmount() {
document.removeEventListener("click", this.closeMenu);
}
openMenu() {
}
closeMenu() {
}
render() {
return (
<div>
<a
href = "javascript:void(0)"
className = "closebtn"
onClick = {this.closeMenu}
>
×
</a>
<div>
Some other structure
</div>
</div>
);
}
}
여기에서는 컴포넌트가 마운트되었을 때 추가한 클릭이벤트 리스너를 삭제합니다.
두 번째는...
import React from 'react';
import { Component } from 'react';
import ReactDom from 'react-dom';
import d3Chart from './d3charts';
export default class Chart extends Component {
static propTypes = {
data: React.PropTypes.array,
domain: React.PropTypes.object
};
constructor(props){
super(props);
}
componentDidMount(){
let el = ReactDom.findDOMNode(this);
d3Chart.create(el, {
width: '100%',
height: '300px'
}, this.getChartState());
}
componentDidUpdate() {
let el = ReactDom.findDOMNode(this);
d3Chart.update(el, this.getChartState());
}
getChartState() {
return {
data: this.props.data,
domain: this.props.domain
}
}
componentWillUnmount() {
let el = ReactDom.findDOMNode(this);
d3Chart.destroy(el);
}
render() {
return (
<div className="Chart">
</div>
);
}
}
여기서 통합하려고 합니다.d3.js에 반응하여componentWillUnmount; DOM 에서 차트 요소를 삭제합니다.
그것 말고도 내가 써본 것은componentWillUnmount오픈 후 부트스트랩모달 청소에 사용합니다.
그 밖에도 많은 사용 사례가 있을 것입니다만, 이러한 사용 사례는componentWillUnMount도움이 됐으면 좋겠어요.
이 간단한 예(React Docs에서 가져온 예)에서는 Clock 컴포넌트의 인터벌을 클리어하기 위해 사용합니다.예를 들어, 페이지에는 2개의 탭이 있으며, 그 중 하나가User Info그리고 두 번째 탭은User Schedule저기에 살아있는 시계가 있어요.로 전환하면User Schedule탭,componentDidMount를 호출하여 타이머를 설정합니다.그리고 일단 당신이 로 다시 전환하면User Info이 인터벌 훅을 유지할 필요가 없으며 언바인드/서브스크라이브 로직을 에 쓸 수 있습니다.componentWillUnmount이벤트입니다.
import React from "react";
export default class Clock extends React.Component {
constructor(props) {
console.log("Clock", "constructor");
super(props);
this.state = {
date: new Date()
};
}
tick() {
this.setState({
date: new Date()
});
}
// These methods are called "lifecycle hooks".
componentDidMount() {
console.log("Clock", "componentDidMount");
this.timerID = setInterval(() => {
this.tick();
}, 1000);
}
// These methods are called "lifecycle hooks".
componentWillUnmount() {
console.log("Clock", "componentWillUnmount");
clearInterval(this.timerID);
}
render() {
return (
<div>It is {this.state.date.toLocaleTimeString()}.</div>
);
}
}
작성 시ComponentsReact를 사용하면 모든 라이브러리가 DOM 관리 철학과 잘 통합되는 것은 아닙니다.
예를 들어 c3와 같은 그래프 라이브러리를 사용하는 것이 있습니다. c3DOM 노드가 주어질 것으로 예상되며 React에서 떨어져 자체 마크업을 작성/관리합니다.이 경우 구성 요소가 DOM에서 제거될 때 이 라이브러리에서 생성된 요소를 정리해야 합니다.
import React, { Component, PropTypes } from 'react';
import c3 from 'c3';
export default class Graph extends Component {
componentDidMount () {
this._initGraph();
}
componentWillUnmount () {
this.graph = this.graph.destroy();
}
_initGraph () {
this.graph = c3.generate({
bindto: this.refs.graph
});
}
render () {
return (
<div className="graph">
<div className="graph__graph" ref="graph"></div>
</div>
);
}
}
여기서 React는 1개를 만듭니다.div의 자리 표시자로서c3콘텐츠를 추가합니다.은 이음음음음음음음음음 the the the the the the the the the the the the에서 시작된다.componentDidMount훅, 정리하다componentWillUnmount.
간단한 솔루션은 다음과 같습니다.
import React from "react"
export default class App extends React.Component {
isMounted = false
componentDidMount(){
this.isMounted = true
if (this.isMounted){
this.setState({'anyState': anyState}) //call setState if component isMounted
}
}
componentWillUnmount(){
this.isMounted = false
}
render(){
return(
<div />
)
}
}
언급URL : https://stackoverflow.com/questions/40760308/how-to-properly-use-componentwillunmount-in-reactjs
'programing' 카테고리의 다른 글
| Rest Client Exception:응답을 추출할 수 없습니다.적절한 Http Message Converter를 찾을 수 없습니다. (0) | 2023.03.29 |
|---|---|
| 확장자가 .js인 파일에서는 JSX가 eslint-config-airbnb에서 허용되지 않습니다. (0) | 2023.03.29 |
| CSS 모듈 및 리액트를 사용한 여러 클래스 이름 (0) | 2023.03.29 |
| .env 파일 변수를 웹 팩 구성에 전달하려면 어떻게 해야 합니까? (0) | 2023.03.29 |
| Unix 쉘 스크립트에서 읽을 수 있는 JSON 형식으로 컬 출력 표시 (0) | 2023.03.29 |