Asynchronous setState

Issue

비동기 작업 중 component가 mount되지 않았을 때, setState를 시도하면 warning이 발생한다.

Example

getData = () => {
    axios.get(query)
    .then((response) => {
        this.setState({ name: "qvil" });
    })
    .catch((error) => {
        console.log(error);
    });
}

Resolve

component life cycle을 이용하여 component가 mount 되었을 때만 setState함수를 사용하여 해결

Component Mounting

constructor() -> componentWillMount() -> render() -> componentDidMount()

Component Unmounting

componentWillUnmount()

Example

constructor(props) {
    super(props);
    this.componentMounted = false;
}

componentWillMount() {
    this.componentMounted = true;
}

componentWillUnmount() {
    this.componentMounted = false;
}

getData = () => {
    axios.get(query)
        .then((response) => {
            if (this.componentMounted) {
                this.setState({ name: "qvil" });
            }
        })
        .catch((error) => {
            console.log(error);
        });
}

Reference

results matching ""

    No results matching ""