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

标签 javascript arrays reactjs react-native

我有一个由不同字符串组成的数组。我想通过它映射并在 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/

相关文章:

javascript - 刷新 Ember 数据更新 View

javascript - 如何循环调用ajax来下载pdf文件?

计算数组中字母出现的次数

django - ReactJS & Django : How can I send csrf token with axios in a proper way?

javascript - IE8 和 IE7 的 onmouseover javascript 不透明度

javascript - 从 promise.all() 返回数据

c# - 我可以用字符串变量(或其他东西)命名数组的每个元素吗?

java - 我的投票系统已经很好但是

css - Material UI TextField 边框与 Label 重叠

html - 无法确定 CSS 的变换比例起点