gpt4 book ai didi

javascript - 将数组中的位置分配为 react 键?

转载 作者:行者123 更新时间:2023-11-29 23:46:34 26 4
gpt4 key购买 nike

我有一个由不同字符串组成的数组。我想通过它映射并在 React 中显示它。当两个字符串相同时,React 不喜欢它。

我的问题是:有没有办法让我通过数组映射并将数组中元素的位置(0,1,2,3..)指定为键?我不确定我将如何访问它?可以吗?

let renderthis = this.props.myreducer.somearray.map((element) =>
<span key={what can I put here?}>{element} </span>
);

顺便说一句,我试过了,但没有用:

let renderthis = this.props.myreducer.somearray.map((element, i) =>
<span key={i}>{element} </span>
);

Warning: flattenChildren(...): Encountered two children with the same key, .1:$afaf. Child keys must be unique; when two children share a key, only the first child will be used.

最佳答案

Array.prototype.map 回调接受第二个参数作为项目索引。

这意味着如果您只需要每个元素集合的唯一键,而您没有任何其他自然唯一的值,您可以简单地这样做:

let renderthis = this.props.myreducer.somearray.map((element, i) =>
<span key={i}>{element} </span>
);

关于javascript - 将数组中的位置分配为 react 键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43794771/

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