JSX 키 속성을 반응 요소에 전달합니다.

15538 단어 reactwebdevbeginners

StockSnap에서 Pixabay의 이미지

개요


  • Introduction
  • Background to Array.prototype.map
  • Using Array.prototype.map to map array of data in react
  • References

  • 소개



    이 문서의 초점은 반응에서 Array.prototype.map의 가장 일반적인 사용 사례에 있습니다.

    Array.prototype.map의 배경



    한동안 반응을 사용했다면 Array.prototype.map 를 사용하여 데이터 배열에서 반응 요소를 동적으로 생성했을 가능성이 큽니다. ES5Array 방법map에 익숙하지 않은 경우 MDN documentation에서 이에 대해 읽을 수 있습니다.
    간단히 말해서:

    The map() method creates a new array populated with the results of calling a provided function on every element in the calling array. MDN



    예를 들어 이름 배열이 있는 경우입니다.

    const firstNames = ["Joseph", "Tom", "Maria", "Chris"];
    

    map 메서드를 사용하여 다음과 같이 각 이름의 문자 수로 구성된 다른 배열을 만들 수 있습니다.

    const charInFirstName = firstNames.map((firstName) => firstName.length);
    console.log(charInFirstName); //[6, 3, 5, 5]
    


    Array.prototype.map을 사용하여 반응 중인 데이터 배열을 매핑합니다.



    같은 방식으로 ES5 배열 방법map을 사용하여 요소 배열을 매핑할 수 있고, 반응에서 데이터 배열을 JSX 요소 배열에 매핑할 수 있습니다Array.prototype.map. map가 이 작업을 수행하는 가장 쉽고 권장되며 가장 일반적으로 사용되는 방법이지만 for 루프 또는 forEach 배열 방법을 사용하여 동일한 결과를 얻을 수도 있다는 점을 지적하는 것이 중요합니다.

    아래 코드에서 오픈 소스 프로젝트에 대한 기여자 배열을 만들었습니다.

    const contributorsList = [
      { name: "Jane Doe", url: "https://www.fakeurl.io" },
      { name: "John Doe", url: "https://www.anotherfakeurl.net" }
    ];
    


    아래 코드에서 중첩된 Contributor 태그가 있는 li 요소를 반환하는 a 구성 요소를 생성하고 Contributor.js 파일에 저장합니다.Contributor.js
    import React from "react";
    export default function Contributor(props) {
      return (
        <li>
          <a href={props.url} target="_blank" rel="noopener noreferrer">
              {props.name}
          </a>
        </li>
      );
    }
    


    또한 App를 가져오는 Contributor 구성 요소도 만들었습니다. 그런 다음 기여자 배열을 구성 요소 배열Contributor에 매핑합니다.App.js
    import React, { useState } from "react";
    import Contributor from "./Contributor";
    const contributorsList = [
      { name: "Jane Doe", url: "https://www.fakeurl.io" },
      { name: "John Doe", url: "https://www.anotherfakeurl.net" }
    ];
    export default function App() {
      const [contributors] = useState(contributorsList);
      return (
        <div className="wrapper">
          <ul>
            {contributors.map((contributor, index) => (
              <Contributor
                name={contributor.name}
                url={contributor.url}
              />
            ))}
          </ul>
        </div>
      );
    }
    
    


    위의 코드는 기여자 목록을 렌더링하지만 경고와 함께 표시됩니다.

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



    반응이 key JSX 속성을 Contributor 에 전달할 것으로 예상하기 때문에 위의 경고가 표시됩니다. key의 값은 각 Contributor 구성 요소를 고유하게 식별하는 문자열이어야 합니다. to the react documentation에 따르면 :

    A key is a special string attribute you need to include when creating lists of elements.



    키는 변경, 삭제 또는 추가된 요소를 식별하는 데 도움이 됩니다. 배열의 요소에 안정적인 ID를 부여합니다. 목록의 요소에 명시적인 키를 제공하지 않으면 react는 기본적으로 요소 인덱스를 키로 사용합니다. 실제로 index 속성의 값으로 key를 전달하면 반응이 사용자가 수행 중인 작업을 알고 있다고 가정하기 때문에 경고가 사라집니다.

    <div className="wrapper">
          <ul>
            {contributors.map((contributor, index) => (
              <Contributor
                key={index}
                name={contributor.name}
                url={contributor.url}
              />
            ))}
          </ul>
        </div>
    


    인덱스를 key 속성의 값으로 전달하면 경고가 사라지지만 배열의 항목 순서가 변경될 경우 요소 인덱스를 키로 사용하는 것은 권장되지 않습니다. react documentation에 따르면 이것은,

    it will negatively impact performance and may cause issues with component state.



    위의 예에서 다음과 같이 색인을 이름에 연결하여 고유 키를 즉석에서 생성할 수 있습니다.

     <div className="wrapper">
          <ul>
            {contributors.map((contributor, index) => (
              <Contributor
                key={contributor.name + index}
                name={contributor.name}
                url={contributor.url}
              />
            ))}
          </ul>
        </div>
    


    일반적으로 map를 사용하여 요소 배열을 만들 때 map에 대한 콜백에서 반환된 요소에는 고유한 JSXkey 특성이 있어야 합니다. keyprop로 전달되지 않는 JSX 속성이라는 점에 유의하는 것도 중요합니다. 구성 요소에서 key 값에 액세스하려면 key 이외의 이름을 가진 소품으로 전달해야 합니다. 배열에 사용되는 키는 형제 간에 고유해야 합니다. 전역적으로 고유할 필요는 없습니다.

    이 문서의 주요 초점은 Array.prototype.map를 사용하여 데이터에서 요소 배열을 만드는 것이지만 for 루프 또는 forEach 배열 메서드를 사용하여 동일한 작업을 수행할 수도 있습니다.

    이 글을 끝까지 읽어주셔서 감사합니다. 기술적으로 부정확한 내용을 발견하면 아래에 의견을 남겨주십시오. 유용하다고 생각되면 다른 플랫폼에서 공유하는 것을 고려하십시오. 다른 사람들도 유용하다고 생각할 수 있습니다.

    참조


  • React documentation
  • Index as a key is an anti-pattern
  • MDN
  • 좋은 웹페이지 즐겨찾기