简体   繁体   English

React,列表中的每个孩子都应该有一个唯一的 key prop

[英]React, Each child in a list should have a unique key prop

So I'm trying to make a to do list and it's not working when I try to add item to the list with addItemToList .所以我正在尝试制作一个待办事项列表,当我尝试使用addItemToList将项目添加到列表时它不起作用。 I am getting this error:我收到此错误:

Each child in a list should have a unique “key” prop

App code:应用代码:

function App() {
  const [currentItem, setCurrentItem] = useState("");
  const [itemlist, updateItemList] = useState([]);

  const onChangeHandler = (e) => {
    setCurrentItem(e.target.value);
  };

  const addItemToList = () => {
    updateItemList([...itemlist, { item: currentItem, key: Date.now() }]);
    setCurrentItem("");
  };

  return (
    <div className="App">
      <header>
        <form id="to-do-form">
          <input
            type="text"
            placeholder="Enter Text"
            value={currentItem}
            onChange={onChangeHandler}
          />
          <button onClick={addItemToList} type="submit">
            Add
          </button>
        </form>
        <List itemlist={itemlist} />{" "}
      </header>
    </div>
  );
}

List code:清单代码:

function List(props) {
  return (
    <div>
      {props.itemlist.map((itemObj) => {
        return <p>{itemObj.item}</p>;
      })}
    </div>
  );
}

Solution to the problem问题的解决方案

Since each item object in your case has already a key prop equal to Date.now() , you could use it, like so:由于您的案例中的每个项目 object 已经有一个等于Date.now()的关键道具,因此您可以使用它,如下所示:

function List(props) {
  return (
    <div>
      {props.itemlist.map((itemObj) => {
        return <p key={itemObj.key}>{itemObj.item}</p>;
      })}
    </div>
  );
}

If you haven't a key prop on your items, you could use index from map , like so:如果您的物品没有关键道具,您可以使用map中的索引,如下所示:

function List(props) {
  return (
    <div>
      {props.itemlist.map((itemObj, index) => {
        return <p key={index}>{itemObj.item}</p>;
      })}
    </div>
  );
}

Related to the comment below与下面的评论相关

It's disappearing because the page gets refreshed when you submit the form.它消失了,因为在您提交表单时页面会刷新。 You need to prevent that behaviour by changing addItemToList like so:您需要通过更改addItemToList来防止这种行为,如下所示:

 const addItemToList = (e) => {
    e.preventDefault();
    updateItemList([...itemlist, { item: currentItem, key: Date.now() }]);
    setCurrentItem("");
  };

You probably have an itemlist.map which transforms this array in jsx element to render.您可能有一个itemlist.map将 jsx 元素中的这个数组转换为渲染。

This element needs an unique key, its a prop that helps react render your list correctly.这个元素需要一个唯一的键,它是一个有助于正确渲染列表的道具。

So, you can pass this prop after map this list {itemlist.map(item => <element key={item.UNIQUE_KEY} />)}所以,你可以在 map 这个列表{itemlist.map(item => <element key={item.UNIQUE_KEY} />)}之后传递这个道具

If you dont have an unique key, you can pass the index of your map, but its not recommended because if you modify this list, react will recalculate all those index again如果您没有唯一键,您可以传递您的 map 的索引,但不建议这样做,因为如果您修改此列表,react 将重新计算所有这些索引

{itemlist.map((item, index) => <element key={index} />)}

This question is a recurring one that has been answered multiple times.这个问题是一个反复出现的问题,已被多次回答。 Please make sure to use the search in advance before posting questions to make sure your question is no duplicate.请确保在发布问题之前提前使用搜索,以确保您的问题没有重复。

But here you go:但在这里你 go:

As the error作为错误

Warning: Each child in a list should have a unique "key" prop.警告:列表中的每个孩子都应该有一个唯一的“关键”道具。

states, React requires children in an array to have a stable identity allowing React to identify which elements have been changed, added or removed during the component lifecycle.状态,React 要求数组中的子元素具有稳定的标识,从而允许 React 识别在组件生命周期中哪些元素已更改、添加或删除。 The identity is assigned to components with the key prop.身份通过key prop 分配给组件。 The docs are very clear about this.文档对此非常清楚。 In fact, it is recommended to use a string that is unique among all list siblings.实际上,建议使用在所有列表兄弟中唯一的字符串。

Assuming that the items have unique names, eg item1 and item2 , you could do something along those lines to use them as component keys when rendering:假设这些项目具有唯一的名称,例如item1item2 ,您可以按照这些方式做一些事情,以便在渲染时将它们用作组件键:

function App(){
  const [currentItem, setCurrentItem] = useState("")
  const [itemlist, updateItemList] = useState([])
  
  const onChangeHandler = e => {
    setCurrentItem(e.target.value)
  };

  const addItemToList = () =>{
    updateItemList([...itemlist, {item: currentItem,  key: Date.now()}])
    setCurrentItem("");
  };

  return itemlist.map((item) => <p key={item.name} />)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 “反应”列表中的每个孩子都应该有一个唯一的“关键”道具 - "react" Each child in a list should have a unique "key" prop React - 列表中的每个孩子都应该有一个唯一的“key”道具 - React - Each child in a list should have a unique “key” prop 列表中的每个孩子都应该有一个唯一的“关键”道具/反应 - Each child in a list should have a unique "key" prop / react 反应错误:列表中的每个孩子都应该有一个唯一的“关键”道具 - React Error: Each child in a list should have a unique "key" prop React - 列表中的每个孩子都应该有一个唯一的“key”道具 - React - Each child in a list should have a unique “key” prop 反应警告:列表中的每个孩子都应该有一个唯一的“关键”道具 - React Warning: Each child in a list should have a unique "key" prop 警告:列表中的每个孩子都应该有一个唯一的“key”道具,即使它有唯一的 key React - Warning: Each child in a list should have a unique “key” prop even tho it has unique key React 反应警告:列表中的每个孩子都应该有一个唯一的“关键”道具不是由地图中缺少关键引起的 - React Warning: Each child in a list should have a unique "key" prop NOT caused by lack of key in map 列表中的每个孩子都应该有一个唯一的“关键”道具错误,以 uuid 作为关键反应 - Each child in a list should have a unique "key" prop error with uuid as key react React - 数组或迭代器中的每个子节点都应该有一个唯一的“key”prop - React - Each child in an array or iterator should have a unique “key” prop
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM