2019-08-21 TIL

2019-08-21 에 적는

8월 19일 ~ 20일의 삽질노트


8월 19일 삽질 (1)

getDerivedStateFromProps는 state를 merge해 업데이트 시킨다. (hooks마냥 return하는 오브젝트로 교체하는 것으로 잘못 알고 있었다)

...
state = { stateOne: "hi", stateTwo: "there" };

...

static getDerivedStateFromProps(nextProps, prevState){
  if ( .. ) {
    return { stateTwo: "floyd" };
    // { ...prevState, stateTwo: "floyd" } 가 아니다!
  }
}

8월 19일 삽질 (2)

optional chaining의 함정

function foo () {
  const testOne = { me: {baz: "hi"} };  
  const testTwo = { me: null };  
  if (testOne.mee?.baz !== testTwo.me?.boo) {  
    console.log('%c 같지 않음!!', 'color:red');  
    return null;  
  }  
  console.log('%c같음!!', 'color:red');
}
  • 기대한 결과 : me가 null이니 조건문의 testOne.mee? 검사하는 순간 조건문을 빠져나와주면 좋겠다.

  • 테스트 결과 : 양변이 같다는 결론이 나온다. -_-

null safe한 건 좋은데, 조건식의 양 변을 모두 체크해 결과를 비교한다. 위 예제의 조건식은 undefined === undefined로 true를 반환한다.

따라서 optional chaining을 너무 남발하거나 맹신하다 보면 버그를 낼 수 있으니 주의하자.


8월 20일 삽질

getDerivedStateFromProps는 return하는 object를 state에 merge한다. async로 선언하면 getDSFP가 항상 Promise를 리턴하기 때문에 state update가 일어나지 않는다.

static async getDerivedStateFromProps (nextProps, prevState) {
  if (prevState.prevId !== nextProps.id) {
    const content = await getUserContent();
    return { userContent: content }; // Promise를 리턴해 state update가 일어나지 않는다
  }
  return null;
}

Minchang Kim
Minchang Kim
웹/앱 개발자 김민창입니다! 좋은 하루 되세요!