[JS] Default parameter 오류

jiseong·2022년 5월 4일
0

T I Learned

목록 보기
238/291

매개변수의 기본값을 활용하면 확장성면에서 장점이 있다. 하지만 단점으로는 null과 같은 falsy한 값들은 그냥 넘겨버리기 때문에 Object.entries 메서드를 호출하는 부분에서 오류가 발생한다.

function jsx(name, attributes = {}, ...children) {
  // 생략 ...
  if (!(node instanceof DocumentFragment)) {
    Object.entries(attributes).forEach(([key, value]) => {
      node.setAttribute(key, value);
    });
  }
}

이유는 바벨이 JSX문법을 변환하는 과정에서 attribute가 없다면 null로 변환해버리기 때문이다.

  • in
const descriptions = items.map(item => (
  <>
    <dt>{item.name}</dt>
    <dd>{item.value}</dd>
  </>
));
  • out
const descriptions = items.map(item =>
  React.createElement(
    React.Fragment,
    null,
    React.createElement("dt", null, item.name),
    React.createElement("dd", null, item.value)
  )
);

에러를 해결해주기 위해서는 메서드를 사용하는 곳에서 falsy한 값들을 처리해야하는데 논리연산자를 사용하면 유용하다.

Object.entries(attributes || {}).forEach(([key, value]) => {
  node.setAttribute(key, value);
});

0개의 댓글