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

时间:2018-09-28 22:32:49

标签: reactjs

我收到此错误,并且不确定所找到的其他解决方案是否适用。我认为发生此错误是因为我在映射时使用了prop并从“结果”中提取了第一个数组,但是我不确定实现此目的的更好方法。请让我知道对此有何更好的做法。我目前正在尝试测试我的搜索框,但由于此错误,我无法执行。

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"
                }
            ]
        }   
    ]

3 个答案:

答案 0 :(得分:1)

尝试为我们的列表项分配一个密钥,这样将解决丢失的密钥问题。

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

根据Official ReactJS Document,原因是他们说:

  

键可帮助React识别哪些项目已更改,添加或删除。应该为数组内的元素赋予键,以赋予元素稳定的身份

例如:

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

选择键的最佳方法是使用一个字符串,该字符串唯一地标识其同级项中的列表项。通常,您会使用数据中的ID作为键:

例如:

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

如果您对呈现的项目没有稳定的ID,则可以将项目索引用作最后的选择:

例如:

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

如果项目的顺序可能会改变,我们不建议使用索引作为键。这可能会对性能产生负面影响,并可能导致组件状态出现问题。查阅Robin Pokorny的文章,深入了解使用索引作为键的负面影响。如果您选择不为列表项分配显式键,那么React将默认使用索引作为键。

希望这些信息可以帮助您澄清问题。

答案 1 :(得分:0)

首先,这不是错误,这是警告。

第二,您在一个循环中渲染Card组件。在这种情况下,您应该为每个组件实例提供唯一的key属性。

例如:

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

答案 2 :(得分:0)

  

Keys帮助React确定哪些项目已更改,添加或正在   删除。

您必须将key属性传递给每个元素:

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

了解有关键的更多信息:Lists and Keys