简体   繁体   English

不知道为什么我会收到“警告:数组或迭代器中的每个子项都应该有一个唯一的“键”道具。”

[英]Not sure why I am getting "Warning: Each child in an array or iterator should have a unique "key" prop."

I am getting this error and I am not sure the other solutions I am finding are applicable.我收到此错误,我不确定我找到的其他解决方案是否适用。 I think this error is occurring because I take the prop and extract the first array from "results" when mapping but I am not sure a better way to achieve this.我认为发生此错误是因为我在映射时使用道具并从“结果”中提取第一个数组,但我不确定有更好的方法来实现这一点。 Please let me know what a better practice for this could be.请让我知道什么是更好的做法。 I am currently trying to test my searchbox but I cannot due to this error.我目前正在尝试测试我的搜索框,但由于此错误而无法测试。

import React, { Component } from 'react';
import CardList from './components/CardList';
import './App.css';
import SearchBox from './components/SearchBox';
import {movies} from './movies';

class App extends Component {
  constructor() {
    super()
    this.state = {
      movies: movies,
      searchfield: ''
    }
  }

  onSearchChange(event) {
    console.log(event.target.value);
  }

  render() {
    return (
      <div className='tc'>
        <h1 className='f1'>Now Playing: </h1>
        <SearchBox searchChange={this.onSearchChange}/>
        <CardList movies={this.state.movies}/>
      </div>
    );
  }
}

export default App;

import React from 'react';
import Card from './card/Card';

const CardList = ({movies}) => {

    const results = movies[0].results;

    return (
        <div>
            {
                results.map((user, i) => {
                    return (
                        <Card 
                            poster={results[i].poster_path} 
                            title={results[i].title} 
                            summary={results[i].overview} 
                        />
                    );
                })
            }
        </div>
    );
}

export default CardList;

export const movies = [
        {
            results: [
                {
                    vote_count: 726,
                    id: 439079,
                    video: false,
                    vote_average: 5.9,
                    title: "The Nun",
                    popularity: 164.352,
                    poster_path: "/sFC1ElvoKGdHJIWRpNB3xWJ9lJA.jpg",
                    original_language: "en",
                    original_title: "The Nun",
                    genre_ids: [
                        27,
                        9648,
                        53
                    ],
                    backdrop_path: "/fgsHxz21B27hOOqQBiw9L6yWcM7.jpg",
                    adult: false,
                    overview: "When a young nun at a cloistered abbey in Romania takes her own life, a priest with a haunted past and a novitiate on the threshold of her final vows are sent by the Vatican to investigate. Together they uncover the order’s unholy secret. Risking not only their lives but their faith and their very souls, they confront a malevolent force in the form of the same demonic nun that first terrorized audiences in “The Conjuring 2,” as the abbey becomes a horrific battleground between the living and the damned.",
                    release_date: "2018-09-05"
                },  
                {
                    vote_count: 163,
                    id: 489999,
                    video: false,
                    vote_average: 7.6,
                    title: "Searching",
                    popularity: 33.883,
                    poster_path: "/9N0T3BaHZNdUCcMZQIM3yMUFwEh.jpg",
                    original_language: "en",
                    original_title: "Searching",
                    genre_ids: [
                        18,
                        53
                    ],
                    backdrop_path: "/qu2IPnFyDztlUOYhCkPptXP1vnv.jpg",
                    adult: false,
                    overview: "After his 16-year-old daughter goes missing, a desperate father breaks into her laptop to look for clues to find her. A thriller that unfolds entirely on computer screens.",
                    release_date: "2018-08-24"
                },

                {
                    vote_count: 349,
                    id: 346910,
                    video: false,
                    vote_average: 5.5,
                    title: "The Predator",
                    popularity: 154.329,
                    poster_path: "/wMq9kQXTeQCHUZOG4fAe5cAxyUA.jpg",
                    original_language: "en",
                    original_title: "The Predator",
                    genre_ids: [
                        27,
                        878,
                        28,
                        35
                    ],
                    backdrop_path: "/f4E0ocYeToEuXvczZv6QArrMDJ.jpg",
                    adult: false,
                    overview: "From the outer reaches of space to the small-town streets of suburbia, the hunt comes home. Now, the universe’s most lethal hunters are stronger, smarter and deadlier than ever before, having genetically upgraded themselves with DNA from other species. When a young boy accidentally triggers their return to Earth, only a ragtag crew of ex-soldiers and a disgruntled science teacher can prevent the end of the human race.",
                    release_date: "2018-09-13"
                }
            ]
        }   
    ]

Try to assign a key to our list items then it will fix the missing key issue.尝试为我们的列表项分配一个键,然后它将解决丢失的键问题。

results.map((user, i) => {
      return (
          <Card 
             key={results[i].id}
             poster={results[i].poster_path} 
             title={results[i].title} 
             summary={results[i].overview} 
          />
      );
  })

The reason is, according to Official ReactJS Document , they said:原因是,根据官方 ReactJS 文档,他们说:

Keys help React identify which items have changed, are added, or are removed.键帮助 React 识别哪些项目已更改、添加或删除。 Keys should be given to the elements inside the array to give the elements a stable identity应为数组内的元素提供键,以使元素具有稳定的身份

For example:例如:

const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) =>
  <li key={number.toString()}>
    {number}
  </li>
);

The best way to pick a key is to use a string that uniquely identifies a list item among its siblings.选择键的最佳方法是使用一个字符串,该字符串在其兄弟项中唯一标识列表项。 Most often you would use IDs from your data as keys:大多数情况下,您会使用数据中的 ID 作为键:

For example:例如:

const todoItems = todos.map((todo) =>
  <li key={todo.id}>
    {todo.text}
  </li>
);

When you don't have stable IDs for rendered items, you may use the item index as a key as a last resort:当您没有呈现项目的稳定 ID 时,您可以将项目索引用作键作为最后的手段:

For example:例如:

const todoItems = todos.map((todo, index) =>
  // Only do this if items have no stable IDs
  <li key={index}>
    {todo.text}
  </li>
);

We don't recommend using indexes for keys if the order of items may change.如果项目的顺序可能发生变化,我们不建议对键使用索引。 This can negatively impact performance and may cause issues with the component state.这会对性能产生负面影响,并可能导致组件状态出现问题。 Check out Robin Pokorny's article for an in-depth explanation of the negative impacts of using an index as a key.查看 Robin Pokorny 的文章,深入了解使用索引作为键的负面影响。 If you choose not to assign an explicit key to list items then React will default to using indexes as keys.如果您选择不为列表项分配显式键,那么 React 将默认使用索引作为键。

Hopefully, this information can help you clarify the issue.希望这些信息可以帮助您澄清问题。

First of all, it is not an error, it is warning.首先,这不是错误,而是警告。

Second, you render Card components in a loop.其次,在循环中渲染Card组件。 In this case you should provide the unique key property to each component instance.在这种情况下,您应该为每个组件实例提供唯一的key属性。

For example:例如:

results.map((user, i) => {
    return (
        <Card
            key={i.toString()}
            poster={results[i].poster_path} 
            title={results[i].title} 
            summary={results[i].overview} 
        />
    );
})

Keys help React identify which items have changed, are added, or are removed. Keys帮助 React 识别哪些项目已更改、添加或删除。

You have to pass key prop to each element:您必须将key prop 传递给每个元素:

results.map(result => (
    <Card 
      key={result.id}
      poster={result.poster_path} 
      title={result.title} 
      summary={result.overview} 
    />
));

Learn more about keys: Lists and Keys了解有关键的更多信息:列表和键

暂无
暂无

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

相关问题 数组或迭代器中的每个子代都应具有唯一的“键”道具。 不知道为什么 - Each child in an array or iterator should have a unique “key” prop. Not sure why 警告:数组或迭代器中的每个子代都应具有唯一的“键”道具。 li中已添加的关键道具 - Warning: Each child in an array or iterator should have a unique “key” prop.; key prop already added in li 数组或迭代器中的每个子代都应具有唯一的“键”道具。 - Each child in an array or iterator should have a unique “key” prop. 警告:数组或迭代器中的每个子代均应具有唯一的“键”道具。 检查“ MovieResults”的渲染方法 - Warning: Each child in an array or iterator should have a unique “key” prop. Check the render method of `MovieResults` index.js:2178警告:数组或迭代器中的每个子代都应具有唯一的“键”属性。 -reactjs - index.js:2178 Warning: Each child in an array or iterator should have a unique “key” prop. - reactjs 警告:数组或迭代器中的每个子代均应具有唯一的“键”道具。 钥匙已经存在 - Warning: Each child in an array or iterator should have a unique “key” prop. Keys are already present 警告:数组或迭代器中的每个子元素都应该有一个唯一的“key”属性。 反应两个按钮功能冲突 - Warning: Each child in an array or iterator should have a unique "key" prop. React two button function conflict 警告:数组或迭代器中的每个孩子都应该有一个唯一的“键”道具。 检查 `ListView` 的渲染方法 - Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `ListView` “警告:”的简单解决方案:数组或迭代器中的每个子代都应具有唯一的“键”道具。 - Simple solution for “Warning: Each child in an array or iterator should have a unique ”key“ prop.”? 警告:数组或迭代器中的每个子代均应具有唯一的“键”道具。 检查`单位`的渲染方法 - Warning: Each child in an array or iterator should have a unique “key” prop. Check the render method of `Units`
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM