error

[React] Warning: Each child in a list should have a unique "key" prop.

wjdwwidz 2023. 11. 3. 17:49

props 렌더링

app의 내부 state를 TOC에 주입함으로써 자동으로 목록이 바뀌게 하는 작업

TOC의 부모가 가진 state값을 이용해서 TOC의 내부 값을 바뀌게 해본다

class App extends Component {
  constructor (props){
    super(props);
    this.state = {
      subject:{title:'WEB', sub:'World Wide Web!'},
      contents:[
        {id:1, title:'HTML', desc:"HTML is for information"},
        {id:2, title:'CSS', desc:'CSS is for design'},
        {id:3, title:'JavaScript', desc:'JavaScript is for interactive'}
      ]
    }
  }

contents를 통해 id, title, desc를 지정해준다

 

TOC에 data라는 props를 통해 값을 전달해준다

 

 

TOC를 열어보면

import React, {Component} from 'react';

class TOC extends Component {
    render() {
      return (
        <nav>
              <ul>
                  <li><a href="1.html">HTML</a></li>
                  <li><a href="2.html">CSS</a></li>
                  <li><a href="3.html">JavaScript</a></li>
              </ul>
          </nav>
      );
    }
  }

  export default TOC;

이렇게 내부적으로 this.props.data 를 갖고 있다.

 

 

이를 render하기 위해서는 while 문으로 props의 개수만큼 반복해준다.

 

while(i < data.length){
        lists.push(<li><a href={"/content/"+data[i].id}>{data[i].title}</a></li>)
        i += 1;
      }

 

 

위처럼 저장 후 리로딩 하였는데 경고메세지가 뜬다.

 

Warning: Each child in a list should have a unique "key" prop.

 

 

Sol ) 

<li>태그 안에 react가 알아볼 수 있는 고유한 key값을 넣어주면 된다.

 

이것은 application 에서 사용하는 값이 아니라 리액트 내부에서 요청하는 것이기 때문에 잘 넣어주기만 하면 저항없이 해결된다.

import React, {Component} from 'react';

class TOC extends Component {
    render() {
      var lists = [];
      var data = this.props.data;
      var i = 0;
      while(i < data.length){
        lists.push(<li key={data[i].id}><a href={"/content/"+data[i].id}>{data[i].title}</a></li>)
        i += 1;
      }
      return (
        <nav>
              <ul>
                  {lists}
              </ul>
          </nav>
      );
    }
  }

  export default TOC;

 

 


 

Key props

index

react공식문서에 보면 index는 최후의 수단 이라는 점을 강조하고 있다. 

 

 

component는 key를 기반으로 갱신/재사용된다는 것을 알 수 있다

 

Unique 의 범위

또한 에러 메세지에서 말하고 있는 unique의 범위가 전역일 필요는 없다.

 

 

react문서 내 지시사항

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.'}
];

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Blog posts={posts} />);

ref : https://ko.legacy.reactjs.org/docs/lists-and-keys.html

 

리스트와 Key – React

A JavaScript library for building user interfaces

ko.legacy.reactjs.org