인덱스와 함께 .map을 사용하여 반응합니다.
다음과 같은 간단한 React 컴포넌트가 있습니다.
import React from 'react';
const ListPage = ({todos}) => (
<div>
<h6>todos</h6>
<ul>
{todos.map(({todo, index}) => (
<li key={index}>{todo}</li>
))}
</ul>
</div>
)
ListPage.propTypes = {
todos: React.PropTypes.array,
};
export default ListPage;
Array.protype.map()의 문서는 두 번째 인수가 currentValue 옆에 index임을 나타냅니다.두 번째 인수를 선택하기 위해 기존 코드를 변경하려면 어떻게 해야 합니까?
다음 작업을 수행해야 합니다.
todos.map((key, index) => { ... })인수 오브젝트 괄호를 사용하지 않습니다.
({todo, index}) => { ... }- 이 구문은 속성을 가져오고 싶다는 것을 의미합니다.todo그리고.index함수의 첫 번째 인수부터요.
구문은 다음과 같습니다.
기본 구문
(param1, param2, …, paramN) => { statements } (param1, param2, …, paramN) => expression // equivalent to: => { return expression; } // Parentheses are optional when there's only one parameter: (singleParam) => { statements } singleParam => { statements } // A function with no parameters requires parentheses: () => { statements }고급 구문
// Parenthesize the body to return an object literal expression: params => ({foo: bar}) // Rest parameters and default parameters are supported (param1, param2, ...rest) => { statements } (param1 = defaultValue1, param2, …, paramN = defaultValueN) => { statements } // Destructuring within the parameter list is also supported var f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c; f(); // 6
알기 쉽게 하기 위한 @Timur Bilalov 답변의 예를 다음에 나타냅니다.
var materials = [
'Hydrogen',
'Helium',
'Lithium',
'Beryllium'
];
materials.map((material,index) => console.log(index +" = " + material + " = " + materials[index]));
산출량
"0 = Hydrogen = Hydrogen"
"1 = Helium = Helium"
"2 = Lithium = Lithium"
"3 = Beryllium = Beryllium"
언급
https://reactjs.org/docs/lists-and-keys.html https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
도움이 되었으면 좋겠다
목록이 동적인 경우 인덱스를 키로 사용하면 안 됩니다. 안티터넌트가 되어 문제가 발생할 수 있습니다.
인덱스는 작성 후 항목을 삭제하거나 작업에 추가할 필요가 없는 경우에만 사용해야 합니다(목록 끝에 항목을 추가하고 삭제하지 않는 경우에만 허용됩니다).그렇지 않으면 Respect에서 자녀를 화해시키는 데 문제가 생길 수 있습니다.
베스트 프랙티스는 모든 작업(증분 또는 UUID)에 "id"를 추가하여 필요한 모든 리액트목록의 키로 사용하는 것입니다.
언급URL : https://stackoverflow.com/questions/36440835/react-using-map-with-index
'programing' 카테고리의 다른 글
| React에서 하위 상태의 상위 상태 액세스 (0) | 2023.03.01 |
|---|---|
| 릴레이셔널 데이터베이스의 행을 삭제해야 합니까, 비활성화해야 합니까? (0) | 2023.03.01 |
| 0이 아닌 1페이지부터 시작하는 스프링 부트 페이지 설정을 하는 방법 (0) | 2023.03.01 |
| Laravel5 Json 파일 내용 가져오기 (0) | 2023.03.01 |
| Angularjs: '구문으로 컨트롤러' 및 $watch (0) | 2023.03.01 |