-
stateJavascript/React.js 2020. 5. 2. 21:59
state
컴포넌트 내부에서 바뀔 수 있는 값이다. props는 부모 컴포넌트가 설정하기 때문에 자식 입장에서는 읽기만 가능하다.
state 주의사항
setState 혹은 useState와 같은 세터 함수로 값을 조작 해야한다. 배열이나 객체를 업데이트 할 때는 해당 자료의 사본을 만들고, 사본을 업데이트 한 후에 그 사본의 상태를 세터 함수에 넣는다.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersconst array = [ {id : 1, value : true}, {id : 2, value : true}, {id : 3, value : false} ]; let nextArray = array.concat({id : 4}); nextArray.filter(item =? item.id != = 2); // id가 1이면 value를 false 처리 // ...은 spread 연산자라고 하며, 객체에 대한 사본을 만들 때 사용한다. nextArray.map(item => (item.id === 1 ? {...item, value : false } : item)); setState
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersimport React, {Component} from 'react'; /* - state 컴포넌트 내부에서 바뀔 수 있는 값 props는 부모 컴포넌트가 설정하기 때문에 자식 입장에서는 읽기만 가능 */ class Counter extends Component { // 생성자 constructor(props) { super(props); // state 초기값 설정 this.state = { number : 0, fixedNumber : 0, }; } render() { const { number, fixedNumber } = this.state; return ( <div> <h1>{number}</h1> <h2>fixed number : {fixedNumber}</h2> <button onClick={() => { // state를 변경해주는 메서드 // 다음과 같은 방식으로 코딩하면 비동기 처리가 가능 // setState의 두 번째 인자는 일종의 콜백함수 this.setState(prevState => { return { number : prevState.number + 1 }; }, () => { console.log('방금 setState가 호출되었습니다.'); console.log(this.state); }); }} > +1 </button> </div> ); } } export default Counter; useState
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersimport React, { useState } from 'react'; /* - useState useState 함수 인자에는 상태의 초기값을 넣어준다. 첫 번째 원소는 현재 상태, 두 번째 원소는 상태를 바꿔주는 함수(Setter function) */ const Say = () => { const [ message, setMessage ] = useState(''); const onClickEnter = () => setMessage('Hi!'); const onClickLeave = () => setMessage('Bye!'); const [ color, setColor ] = useState(''); return( <div> <button onClick={onClickEnter}>Enter</button> <button onClick={onClickLeave}>Leave</button> <h1 style={{ color }}>{message}</h1> <button style={{ color : 'red' }} onClick={() => setColor('red')}>red</button> <button style={{ color : 'green'}} onClick={() => setColor('green')}>green</button> <button style={{ color : 'blue'}} onClick={() => setColor('blue')}>blue</button> </div> ) } export default Say; 'Javascript > React.js' 카테고리의 다른 글
ref (0) 2020.05.03 event (0) 2020.05.02 class component & props (0) 2020.05.02 JSX (0) 2020.05.02 react 7 (0) 2020.01.09