본문으로 바로가기

this.setState

category 개발/React 2019. 7. 3. 16:55

this.setState는 async , 비동기로 작동한다.

test = () => {
	let num = 5;
	console.log(num);
    
    this.setState({
    	num: num - 1;
    });
    
    console.log(num);
}

위와 같을 경우 
콘솔에는 5, 4가 찍히지 않을것이다. 
setState는 비동기이므로 setState()를 실행하고 완료를 기다리지 않고 바로 console.log()를 수행한다.

setState는 state를 변화시키고 렌더링을 하는데
콜백함수를 추가해주면 콜백함수 실행 된 후 리렌더링을 한다.

test = () => {
	let num = 5;
	console.log(num);
    
    this.setState({
    	num: num - 1;
    }, () => {
    	console.log('callback fn');
    });
}

 

'개발 > React' 카테고리의 다른 글

Redux  (0) 2019.06.26
Reducer  (0) 2019.06.25
JSX  (0) 2019.06.22
Actions  (0) 2019.06.21
Views와 Controller-Views  (0) 2019.06.21