State : props는 부모에서 전달되는 바뀔 수 없는 값을 의미하며, state는 컴포넌트 내부에서 바뀔 수 있는 값이다.
클래스형 컴포넌트의 state
1. constructor 메서드를 작성하여 state를 작성하는 방법
class CounterComponent extend Component{
/** 컴포넌트 생성자로 반드시 super(props)를 호출하면 컴포넌트가 상속받는 리엑트의
Component 클래스가 지닌 생성자 함수를 호출한다. */
constructor(props) {
super(props);
// 객체형식의 state 초깃값을 설정한다.
this.state = { num : 0 , fixedNum : 0 }
};
render() {
// state를 조회 시 this.state로 조회한다.
const { num, fixedNum } = this.state;
return (
<div>
<h1>{ num }</h1>
<h2>바뀌지 않는 값 : { fixedNum }</h2>
<button
onClick = {() => {
// onClick을 통하여 버튼이 클릭 되었을 때 this.setState를 사용하여 state에 새로운 값을 넣는다.
this.setState({ num : num + 1 })
}}
> + 1 </button>
</div>
)}
}
class CounterComponent extend Component{
// state를 constructor에서 꺼내어 초깃값을 지정한다.
state = { num : 0 , fixedNum : 0 } ;
render() {
// state를 조회 시 this.state로 조회한다.
const { num, fixedNum } = this.state;
return (
<div>
<h1>{ num }</h1>
<h2>바뀌지 않는 값 : { fixedNum }</h2>
<button
onClick = {() => {
// onClick을 통하여 버튼이 클릭 되었을 때 this.setState를 사용하여 state에 새로운 값을 넣는다.
this.setState({ num : num + 1 })
}}
> + 1 </button>
</div>
)
}
}
this.setState( prevState => { return { num : prevState.num + 1 } })
this.setState( { num : num + 1 } , () => { console.log( “콜백함수 실행!!!” ) })
/* 1 */
const array = [ 1 , 2 ];
const one = array[0];
const two = array[1];
/* 2 */
const array = [ 1 , 2 ];
const [one, two] = array;
const Say = () => {
// 상태 초기값을 넣어준다. 이 때 클래스 컴포넌트의 경우 객체형태만 넘겨줄 수 있었지만, 함수형 컴포넌트는 반드시
// 객체일 필요가 없다
const [text, setText] = useState(‘’);
const onClickE = () => setText(“Hello”);
const onClickL = () => setText(“Bye”);
// 한 컴포넌트에 다수의 state를 사용할 수 있다.
const [color, setColor] = useState(“black”);
const onChangeB = () => setColor(“yellow”);
const onChangeG = () => setColor(“green”);
return (
<div>
<button onClick={ onClickE }>입장</button>
<button onClick={ onClickL }>퇴장</button>
<button onClick={ onChangeB }>파란색</button>
<button onClick={ onChangeG }>초록색</button>
<h1 style={{ color }}> { text } </h1>
</div>
)
}
/* 객체 예시 - 사본을 만든 후 b를 업데이트 한다. */
const obj = { a : 1, b : 2, c : 3, d : 4};
const nextObj = { …obj, b : 1 };
/* 배열 예시 */
const array = [ {id : 1, value : true} , {id : 2, value : true} , {id : 3, value : true}]
/* 1. Array 사본에 4의 id를 추가한다. */
let nextArray = array.concat ({ id : 4 });
/* 2. filter를 활용하여 일치하는 항목 즉 true인 것만 남기고 제외시는 형식으로 사본에 id가 2인 항목을 제거한다. */
nextArray.filter( item => item.id !== 2 )
/* 3. .map을 활용해 배열 내 요소의 모든값을 확인해 주어진 함수에 대한 값을 도출해내는 형식으로,
id값이 1인 항목의 value를 false로 변경한다. */
nextArray.map( item => (item.id === 1 ? { …item, value : false } : item) );