gpt4 book ai didi

javascript - React,使用带有索引的 .map

转载 作者:行者123 更新时间:2023-12-03 13:00:47 25 4
gpt4 key购买 nike

我有一个简单的 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.prototype.map() 的文档显示第二个参数是索引,紧邻 currentValue。如何改变现有代码来获取第二个参数?

最佳答案

您需要这样做:

todos.map((key, index) => { ... }) 不带对象括号作为参数。

({todo, index}) => { ... } - 该语法意味着您想要获取属性 todoindex 来自函数的第一个参数。

您可以看到语法here :

基本语法

 (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

关于javascript - React,使用带有索引的 .map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36440835/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com