๐Ÿ”ซ LifeCycle

์Šคํฌ๋ฆฐ์ƒท, 2019-08-05 21-44-35.png

  • ์ƒ์„ฑ๋ ๋•Œ

    • constructor(์ƒ์„ฑ์žํ•จ์ˆ˜) ์ปดํผ๋„ŒํŠธ๊ฐ€ ๊ฐ€์žฅ ์ฒ˜์Œ ๋งŒ๋“ค์–ด ์งˆ๋•Œ ํ˜ธ์ถœ๋˜๋Š” ํ•จ์ˆ˜
      this.state ๊ฐ’์„ ์„ค์ •, this ๋ฐ”์ธ๋”ฉ ํ•˜๋Š” ์—ญํ• 

    • getDerivedStateFromProps (ํ˜„์žฌ ์ƒํƒœ๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ๋Š”)

    • render ํ•œ๋ฒˆ ์ ๊ฒ€?

        render() {
         return <div>Hello</div>
         }
    • componentDidMount (๋ณด์—ฌ์คŒ)

  • ์—…๋ฐ์ดํŠธ ํ• ๋•Œ

    • getDerivedStateFromProps

    • shouldComponentUpdate (true, false๋ฅผ ์ด์šฉํ•˜์—ฌ ๊ฐ’์ด true๋ฉด ๋‹ค์Œ์œผ๋กœ๋„˜๊ธฐ๊ณ  ์•„๋‹ˆ๋ฉด
      ๊ฐ€์ง€๊ณ  false๋กœ ๋‚ ๋ ค๋ฒ„๋ฆผ๋‹ˆ๋‹ค)

    • render

    • getSnapshotBeforeUpdate(๋ธŒ๋ผ์šฐ์ € ์ œ์ถœ์ง์ „์— DOM์— ์ ‘๊ทผ๊ฐ€๋Šฅ, ์–ด๋–ค ๊ฐ’์„ ๋ฆฌํ„ดํ•˜๊ฒŒ๋˜๋ฉด
      componentDidUpdate ์—์„œ ํ™•์ธ์ด ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค)

  • ์ œ๊ฑฐํ• ๋•Œ

    • componentWillUnmount (์ปดํผ๋„ŒํŠธ๊ฐ€ ์‚ฌ๋ผ์ง€๊ธฐ ์ง์ „์— ํ˜ธ์ถœ, ๋“ฑ๋ก๋œ ์ปดํผ๋„ŒํŠธ ์ œ๊ฑฐ)

๐Ÿฎ componentDidCatch

์—๋Ÿฌ ๋ฐœ์ƒ ์ฐพ๊ธฐ
์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•˜๊ฒŒ ๋˜๋ฉด ๋ธŒ๋ผ์šฐ์ € ์ƒ์—์„œ๋Š” ํฐ ๋ฐ”ํƒ•ํ™”๋ฉด์ž…๋‹ˆ๋‹ค. ๊ทธ๋Ÿฌ๋ฏ€๋กœ ์ง๊ด€์ ์œผ๋กœ ๋ณด์—ฌ์ฃผ๊ฒŒ ํ•˜๋ ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค.

  • main.js


import React from "react";
import User from "./User";
import ErrorBoundary from "./ErrorBoundary";
import ReactDOM from "react-dom";

function App() {
  const user = {
    id: 1,
    username: "suyang"
  };
  return (
    <ErrorBoundary>
      <User />
    </ErrorBoundary>
  );
}

export default App;

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
  • User.js
import React from "react";

function User({ user }) {
  return (
    <div>
      <div>
        <b>ID</b>: {user.id}
      </div>
      <div>
        <b>Username</b>: {user.username}
      </div>
    </div>
  );
}
export default User;
  • ErrorBoundary.js
import React, { Component } from "react";

class ErrorBoundary extends Component {
  state = {
    error: false
  };

  componentDidCatch(error, info) {
    console.log("err");
    console.log({
      error,
      info
    });
    this.setState({
      error: true
    });
  }

  render() {
    if (this.state.error) {
      return <h1>์—๋Ÿฌ๋ฐœ์ƒ</h1>;
    }
    return this.props.children;
  }
}

export default ErrorBoundary;