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');
});
}