【问题标题】:How to make key value of map function increment for each element in JavaScript如何使 JavaScript 中每个元素的 map 函数的键值递增
【发布时间】:2019-04-04 02:05:21
【问题描述】:

我正在映射字段数组中的每个字段,以便每个字段都有一个从 1...n 个字段开始的 id。

我使用它,因为我将所有字段值存储在一个数组中,当一个字段发生更改时,我希望 data[index] 相应地更新。

这是我的地图功能代码

{this.state.fields.map((field) => {
return (
    <IssueInputRow
        labelText={field.name}
        key={i}   //want this to increment by 1 for each field, starting a 0                 
        handler={this.handler}
    />
    );
})}

我希望每个字段的键从 0 开始增加 1。 因此,如果有 3 个字段,则相应字段的键应为 0,1,2。

请告诉我这是怎么可能的

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

在 JavaScript 中,ma​​p 函数有两个参数,一个是 item,第二个是 key。 您需要始终提供这两个参数,否则它将在您的控制台中显示错误。 Item 会返回数组的值,Key 会返回从 0 开始的下标值。

你可以这样做 ->

{this.state.fields == undefined ? '' : this.state.fields.map((field, i) => {
    return (
        <IssueInputRow
         labelText={field.name}
         key={i}  //Here key (i) will give you the value starting from 0           
         handler={this.handler}
        />
    );
 })} 

为了更好地理解地图,请参阅 -> enter link description here

【讨论】:

    【解决方案2】:

    map 的函数的第二个参数是数组索引,所以你可以使用它。

    {this.state.fields.map((field, i) => {
      return (
        <IssueInputRow
          labelText={field.name}
          key={i}             
          handler={this.handler}
        />
      );
    })}
    
    猜你喜欢
    • 1970-01-01
    • 2018-01-28
    • 2021-12-11
    • 2016-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-31
    • 1970-01-01
    相关资源
    最近更新 更多