ReactJS:在数组元素中提供键的最佳方法是什么 [英] ReactJS : What is the best way to give keys in array element

查看:34
本文介绍了ReactJS:在数组元素中提供键的最佳方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是从ReactJS开始,并尝试了类似的其他问题的解决方案,但到目前为止还算不上成功.

I am just starting with ReactJS and tried solutions of other questions similar to this but no luck so far.

这是我的工作代码:

import React from 'react';
import ReactDOM from 'react-dom';


const Numbers = ['2', '4', '6', '8'];

const NumbersList = (props) => (
   <ul>
      {
          props.Numbers.map (
             number => <li key={number}>{number * 2}</li>
          )
      }
    </ul>
)
ReactDOM.render(<NumbersList Numbers = {Numbers} />, document.getElementById('root') )

但是当我将Numbers Array传递为:

But when I am passing Numbers Array as :

const Numbers = ['4', '4', '6', '8']

我收到此错误:

警告:遇到两个具有相同键 4 的孩子.密钥应该是唯一的,以便组件在更新过程中保持其身份.

Warning: Encountered two children with the same key, 4. Keys should be unique so that components maintain their identity across updates.

所以我的问题是:在这种情况下,提供密钥的最佳方法是什么?如果我将数字(如上例所示)用作键,那么避免此警告的最佳解决方案是什么?

So my Question is : What is the best way to give keys in this situation? And if I am using Number (as in above example) as Keys, what is the best solution to avoid this warning?

谢谢!

推荐答案

当您没有商品的明确唯一属性(非唯一基元列表)时,可以使用索引.

When you don't have a definitive unique property for the items (a list of non unique primitives), you can use the index.

注意:如果项目具有唯一的 id (并且应该是非原始列表),则不要使用索引,因为它是

Note: don't use the index if the items have a unique id (and a non-primitives list should), because it's an anti-pattern.

const Numbers = ['2', '4', '4', '8'];

const NumbersList = (props) => (
  <ul>
  {
  props.Numbers.map (
    (number, index) => <li key={index}>{number * 2}</li>
  )}
  </ul>
)

ReactDOM.render(
  <NumbersList Numbers = {Numbers} />,
  document.getElementById('root')
)

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

这篇关于ReactJS:在数组元素中提供键的最佳方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆