Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
112 views
in Technique[技术] by (71.8m points)

javascript - React, using .map with index

I have a simple React component like so:

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;

I can see that the docs for Array.prototype.map() shows that the second argument is index, next to currentValue. How does one alter the existing code to pick up the second argument?

question from:https://stackoverflow.com/questions/36440835/react-using-map-with-index

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to to this:

todos.map((key, index) => { ... }) without object brackets for arguments.

({todo, index}) => { ... } - that syntax means that you want to get properties todo and index from first argument of function.

You can see syntax here:

Basic syntax

(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 }

Advanced syntax

// 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...