python만 사용하다가 javascript를 사용하니... 데이터를 조작하는 어려움이 확실히 있다.
dictionary key를 기준으로 정렬하는것도 내가 구현해야하는건가..

const unordered = {
  'b': 'foo',
  'c': 'bar',
  'a': 'baz'
};

console.log(JSON.stringify(unordered));
// → '{"b":"foo","c":"bar","a":"baz"}'

const ordered = {};
Object.keys(unordered).sort().forEach(function(key) {
  ordered[key] = unordered[key];
});

console.log(JSON.stringify(ordered));

key는 element의 리스트를 사용할때 꼭 명시해줘야 한다. 아래 소스코드를 참고하면 

function NumberList(props) {
  const numbers = props.numbers;
  const listItems = numbers.map((number) =>
    <li key={number.toString()}>
      {number}
    </li>
  );
  return (
    <ul>{listItems}</ul>
  );
}

위에서 li의 element에서 key를 사용하지 않으면 경고가 표시된다. 

React에서 Key의 역할은 어떤 항목을 변경, 추가 또는 삭제할지 식별하는 것을 돕는다. 그렇기 때문에 리스트 element에서 값의 업데이트를 위해서는 반드시 적어줘야 하는데, 이때 각각 element는 고유한 key를 갖고 있어야 하고, 보통은 데이터의 id를 사용한다. 

id가 없다면 최후의 수단으로 항목의 index를 키로 사용할 수 있는데, 이렇게 사용하면 성능이 저하되거나 컴포넌트의 state와 관련한 문제가 발생할 수 있으니 명시적으로 id를 적어주는게 좋다.

위에서 index를 지정하지 않으면 경고가 뜬다고 했는데, 그 이유도 기본으로 index를 key로 사용하기 때문에 표시되는 방법이다. (권장하지 않는다는 뜻!)

컴포넌트 추출하기

컴포넌트로 Blog를 추출하고 리스트의 값을 표시하기 위해서는 아래와 같이 코드를 작성하면 된다.

function ListItem(props) {  
  return <li>{props.value}</li>;
}

function NumberList(props) {
  const numbers = props.numbers;
  const listItems = numbers.map((number) => 
    <ListItem key={number.toString()}
              value={number} />

  );
  return (
    <ul>
      {listItems}
    </ul>
  );
}

const numbers = [1, 2, 3, 4, 5];
ReactDOM.render(
  <NumberList numbers={numbers} />,
  document.getElementById('root')
);
function Blog(props) {
  const sidebar = (
    <ul>
      {props.posts.map((post) =>
        <li key={post.id}>
          {post.title}
        </li>
      )}
    </ul>
  );
  const content = props.posts.map((post) =>
    <div key={post.id}>
      <h3>{post.title}</h3>
      <p>{post.content}</p>
    </div>
  );
  return (
    <div>
      {sidebar}
      <hr />
      {content}
    </div>
  );
}

const posts = [
  {id: 1, title: 'Hello World', content: 'Welcome to learning React!'},
  {id: 2, title: 'Installation', content: 'You can install React from npm.'}
];
ReactDOM.render(
  <Blog posts={posts} />,
  document.getElementById('root')
);
 

+ Recent posts