Component Lifecycle - MoonGyeongHyeon/React_Study GitHub Wiki
React - Component Lifecycle
์์ (1,2)์์ Component Lifecycle์ ์ด์ฉํ์ฌ ๊ตฌํํ ๋ถ๋ถ์ด ์์๋ค. ์ด๋ฒ์ ์ข ๋ ์์ธํ ์์๋ณด๋๋ก ํ์.
Component ์์ฑ
์ปดํฌ๋ํธ๊ฐ ์์ฑ๋ ๋ constructor -> componentWillMount -> render -> componentDidMount
์์ผ๋ก ํธ์ถ์ด ๋๋ค. ์ปดํฌ๋ํธ๊ฐ ์ ๊ฑฐ๋ ๋์ componentWillUnmount
๋ง ํธ์ถ๋๋ค.
props, state๊ฐ ๋ณ๊ฒฝ๋ ๋
์ปดํฌ๋ํธ์ props๊ฐ ๋ณ๊ฒฝ๋ ๋ componentWillReceiveProps -> shouldComponentUpdate -> componentWillUpdate-> render -> componentDidUpdate
์์ผ๋ก ํธ์ถ์ด ๋๋ค. state์ ๊ฒฝ์ฐ, shouldComponentUpdate
๋ถํฐ ํธ์ถ์ด ๋๋ค.
์ ์ฒด ๊ณผ์
๊ฐ ๋ฉ์๋ ์ค๋ช
-
constructor
constructor(props){ super(props); console.log("constructor"); }
์์ฑ์๋ก ์ปดํฌ๋ํธ๊ฐ ์ฒ์ ๋ง๋ค์ด์ง ๋ ํธ์ถ๋๋ค. ๊ธฐ๋ณธ state๋ฅผ ์ด๊ธฐํํ ์ ์๋ค.
โ
-
componentWillMount
componentWillMount(){ console.log("componentWillMount"); }
์ปดํฌ๋ํธ๊ฐ DOM ์์ ๋ง๋ค์ด์ง๊ธฐ ์ ์ ํธ์ถ๋๋ค.
โ
-
render
์ปดํฌ๋ํธ ๋ ๋๋ง์ ๋ด๋นํ๋ค.
โ
-
componentDidMount
componentDidMount(){ console.log("componentDidMount"); }
์ปดํฌ๋ํธ๊ฐ ๋ค ๋ง๋ค์ด์ง๊ณ ์ฒซ ๋ ๋๋ง๊น์ง ๋๋ ํ ํธ์ถ๋๋ค. ์ฌ๊ธฐ์ ๋ค๋ฅธ Javascript ํ๋ ์์ํฌ๋ฅผ ์ฐ๋ํ๊ฑฐ๋ setTimeout, setInterval ๋ฐ AJAX ์ฒ๋ฆฌ ๋ฑ์ ์ํํ๋ค.
โ
-
componentWillRecevieProps
componentWillReceiveProps(nextProps){ console.log("componentWillReceiveProps: " + JSON.stringify(nextProps)); }
์ปดํฌ๋ํธ๊ฐ ์๋ก์ด props๋ฅผ ๋ฐ์์ ๋ ํธ์ถ๋๋ค. props์ ๋ฐ๋ผ state๋ฅผ ์ ๋ฐ์ดํธํด์ผ ํ ๋ ์ฌ์ฉํ๋ฉด ์ ์ฉํ๋ค. ํ์ฌprops (
this.props
) ์ ๋ค์ props (nextProps
) ๋ฅผ ์ ์ ํ ์ด์ฉํ๋๋ก ํ์. ์ด ์์์this.setState
๋ฉ์๋๋ฅผ ํธ์ถํด๋ ์ถ๊ฐ์ ์ธ ๋ ๋๋ง์ ์งํํ์ง ์๋๋ค.โ
-
shouldComponentUpdate
shouldComponentUpdate(nextProps, nextState){ console.log("shouldComponentUpdate: " + JSON.stringify(nextProps) + " " + JSON.stringify(nextState)); return true; }
props ๋๋ state๊ฐ ๋ณ๊ฒฝ๋์ ๋, ๋ฆฌ๋ ๋๋ง ํ ์ง ๋ง์ง๋ฅผ ์ ํ๋ ๋ฉ์๋์ด๋ค. ๋ฐํ ๊ฐ์ ๋ฐ๋ผ ๊ฒฐ์ ๋๋ค.
return nextProps.id !== this.props.id;
์ฒ๋ผ ํน์ ํ๋๋ง์ ๋น๊ต/ํ์ธ ํ ์๋ ์๊ณ ,JSON.stringify()
๋ฅผ ์จ์ ์ฌ๋ฌ ํ๋๋ฅผ ๋น๊ต ํ ์๋ ์๋ค.์ฐธ๊ณ ๋ก, React ๊ณต์ ๋ฌธ์์์
JSON.stringify()
๋ฅผ ํตํ ๋น๊ต๋ ๋งค์ฐ ๋นํจ์จ์ ์ด๊ณ ์ฑ๋ฅ์ ์ ์ํฅ์ ๋ผ์น๊ธฐ ๋๋ฌธ์ ๊ถ์ฅํ์ง ์๋๋ค.โ
-
componentWillUpdate
componentWillUpdate(nextProps, nextState){ console.log("componentWillUpdate: " + JSON.stringify(nextProps) + " " + JSON.stringify(nextState)); }
์ปดํฌ๋ํธ๊ฐ ์ ๋ฐ์ดํธ๋๊ธฐ ์ ์ ์คํ๋๋ค. ์ฌ๊ธฐ์ ๋ง์ฝ
this.setState
๋ฅผ ํธ์ถํ ๊ฒฝ์ฐ ๋ฌดํ๋ฃจํ์ ๋น ์ง๊ฒ ๋๋ ์ฃผ์ํ๋๋ก ํ์.โ
-
componentDidUpdate
componentDidUpdate(prevProps, prevState){ console.log("componentDidUpdate: " + JSON.stringify(prevProps) + " " + JSON.stringify(prevState)); }
์ปดํฌ๋ํธ๊ฐ ๋ฆฌ๋ ๋๋ง์ ๋ง์น ํ ํธ์ถ๋๋ค.
โ
-
componentWillUnmount
componentWillUnmount(){ console.log("componentWillUnmount"); }
์ปดํฌ๋ํธ๊ฐ DOM์์ ์ฌ๋ผ์ง ํ ํธ์ถ๋๋ค.