【问题标题】:How can I make a map function inside lodash .times如何在 lodash .times 中创建地图功能
【发布时间】:2019-03-18 16:39:50
【问题描述】:

我正在尝试为我从 _.times 内的 API 响应中获得的项目创建一个映射函数,但它不起作用,即使有可能,我只想为每个项目创建一个唯一的 ID 号,并且将每个 id 与每个项目的 className 中的 this.state.selected 进行比较

<div className="items">
  {_.times(this.state.items.length, j => ({this.state.items.map(i =><a href="/" id={j} onClick={this.targetValue} className={this.state.selected === j ? "selected" : ""}>{i.name}</a>)}))}
</div>

【问题讨论】:

  • 映射时是否可以只使用索引?虽然不理想,但我不太确定您要达到的目标,除非您能举出更好的例子

标签: reactjs ecmascript-6 lodash


【解决方案1】:

工作正常 -

    render() {
       return (_.times(this.state.items.length, j => this.state.items.map(i => <div>
          <a id={j} href="" className={j === this.state.selected ? "selected": ""}>{i}</a> . 
       </div>)))
    }

https://jsfiddle.net/kpcqn7wb/

请注意,您的变量“j”不是唯一的 - 它是函数调用的计数索引对调用 _.times 的函数,因此 id attr 不会是唯一的。

【讨论】:

    【解决方案2】:

    正如 Win 在评论中提到的,最简单的可能就是使用普通的 _.map() 调用 this.state.items,并利用每个数组项的索引来设置 id。请记住,lodash 在迭代时几乎总是提供两个参数:在数组中是 (value, index),在对象中是 (value, key)

    在这种情况下,您可以执行以下操作:

    <div className="items">
      {_.map(this.state.items, (item, index) =>{
        return(
        <a href="/" id={index} onClick={this.targetValue} className={this.state.selected === index ? "selected" : ""}>{item.name}</a>
        );
      });
      }
    </div>

    这有帮助吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-29
      相关资源
      最近更新 更多