react class vs function style
reactはコンポーネントから構成されています.
このとき,素子を表現する方法は2つある.
クラス構成部品
かんすうがたそし
従来、関数型素子はクラス素子に比べてstate、lifecycleなどの機能を実行できなかったが、これらの不足を補う「反フック」機能が追加されたため、関数型素子とクラスコンピュータの違いは大きくなかった.逆に関数型素子の利便性のため,クラス素子よりも多く用いられ,推奨されている.
ライフサイクルは次の順序で行われます. compoenentWillMount() : compoenetWillMount()
構成部品を作成する前に何かを処理する必要がある場合は、ComponentWillMount()という方法を使用して構成部品を作成する前に実行します.つまり、レンダリングが呼び出される前に必要なことを実行します. render():レンダリングメソッドが呼び出されたときにマウントされます.画面に描かれます コンポーネントDidMount():コンポーネントを実装する開発者が実装することで、コンポーネントを作成した後に必要なことを処理できます. <ステータスの変更> shouldComponentUpdate(NextProps,NextState): を返し、レンダリングを呼び出す必要があるかどうかを返します. componentWillUpdate(nextProps,nextState) render() componentDidUpdate(prevProps,prevState) <素子が消失した場合> componentWillUnmount() ステータスを初期化し、値をsetStateに変更します. 関数型では、Effectを使用して「コンポーネントDidMount、コンポーネントDidUpdate」などのライフサイクルを実行します. は2番目のパラメータ[]として空の配列を入れ、最初の描画時にのみ呼び出されます.「componentDidMount」のように. 関数が userEffectの最初のパラメータの関数として返されると、cleanupポイントで呼び出され、「componentWillUnMount」などの機能が実行されます. 関数型はusStateを使用して値を変更、管理します.
このとき,素子を表現する方法は2つある.
クラス構成部品
かんすうがたそし
従来、関数型素子はクラス素子に比べてstate、lifecycleなどの機能を実行できなかったが、これらの不足を補う「反フック」機能が追加されたため、関数型素子とクラスコンピュータの違いは大きくなかった.逆に関数型素子の利便性のため,クラス素子よりも多く用いられ,推奨されている.
class型素子とfunction型素子のライフサイクル
import React ,{useState, useEffect} from 'react';
import './App.css';
function App() {
let [funcShow,setFuncShow] = useState(true);
let [classShow,setClassShow] = useState(true);
return (
<div className="container">
<h1>Hello World</h1>
<input type="button" value="func" onClick={
function(){
setFuncShow(!funcShow)
}
}></input>
<input type="button" value="class" onClick={
function(){
setClassShow(!classShow)
}
}></input>
{funcShow ? <FuncComp initNumber={2}></FuncComp> : null}
{classShow ? <ClassComp initNumber={2}></ClassComp> : null}
</div>
);
}
class component
ライフサイクルは次の順序で行われます.
構成部品を作成する前に何かを処理する必要がある場合は、ComponentWillMount()という方法を使用して構成部品を作成する前に実行します.つまり、レンダリングが呼び出される前に必要なことを実行します.
//클래스형
let classStyle = 'color:red';
class ClassComp extends React.Component{
//state, setState 사용
state = {
number: this.props.initNumber,
date : (new Date()).toString()
}
componentWillMount(){
//%c는 클래스스타일주기위해
console.log('%cclass => componentWillMount',classStyle);
}
componentDidMount(){
console.log('%cclass => componentDidMount',classStyle);
}
//상태변경시
shouldComponentUpdate(nextProps, nextState){
console.log('%cclass => shouldComponentUpdate',classStyle);
return true;
}
componentWillUpdate(nextProps, nextState){
console.log('%cclass => componentWillUpdate',classStyle);
}
componentDidUpdate(nextProps, nextState){
console.log('%cclass => componentDidUpdate',classStyle);
}
//컴포넌트 소멸
componentWillUnmount(){
console.log('%cclass => componentWillUnMount',classStyle);
}
//render 메소드
render(){
console.log('%cclass => render',classStyle);
return(
<div className="container">
<h2>class style</h2>
<p>Number : {this.state.number}</p>
<p>Date : {this.state.date}</p>
<input type="button" value="random" onClick={
function(){
//this.setState에 새로운값을 넘겨줘서 state 업데이트
this.setState({number:Math.random()})
}.bind(this)
}></input>
<input type="button" value="date" onClick={
function(){
this.setState({date:(new Date()).toString()})
}.bind(this)
}></input>
</div>
)
}
}
export default App;
クラスでは、state、setStateを使用してステータス管理を行います.function component
//함수형 훅 이용
let funStyle = 'color:blue';
let funId = 0;
function FuncComp(props){
//useState사용
let [number,setNumber] = useState(props.initNumber);
let [date,setDate] = useState((new Date()).toString())
//useEffect는 compoenentDidMount 와 componentDidUpdate와 같은 효과
useEffect(function(){
console.log('%cfunction => useEffect (componentDidMount & componentDidUpdate) '+ (++funId),funStyle);
//clean up : return 이용
//clean up 이 함수에 대한 내용을 실행한 것을 정리할때 return값을 호출해준다.
return function(){
console.log('%cfunction => useEffect return (componentDidMount & componentDidUpdate) '+ (++funId),funStyle);
}
})
//컴포넌트가 최초생성될 때 딱 한번만 실행
useEffect(function(){
console.log('%cfunction => useEffect (componentDidMount) '+ (++funId),funStyle);
//컴포넌트 소멸
return function(){
console.log('%cfunction => useEffect return (componentWillUnMount) '+ (++funId),funStyle);
}
},[])
//number변경될때 실행
useEffect(function(){
console.log('%cfunction => useEffect number (componentDidMount & componentDidUpdate) '+ (++funId),funStyle);
return function(){
console.log('%cfunction => useEffect number return (componentDidMount & componentDidUpdate) '+ (++funId),funStyle);
}
},[number])
console.log('%cfunction => render '+ (++funId),funStyle);
return(
<div className="container">
<h2>function style component</h2>
<p>Number : {number}</p>
<p>Date : {date}</p>
<input type="button" value="random" onClick={
()=>{
setNumber(Math.random());
}
}></input>
<input type="button" value="date" onClick={
()=>{
setDate((new Date()).toString());
}
}></input>
</div>
)
}
const [number,setNumber] = useState(props.initNumber);
Reference
この問題について(react class vs function style), 我々は、より多くの情報をここで見つけました https://velog.io/@dbsbest10/react-class-vs-function-styleテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol