【问题标题】:Can anyone explain why I'm getting the error about "same key"谁能解释为什么我收到有关“相同密钥”的错误
【发布时间】:2021-11-21 12:47:06
【问题描述】:

我正在做我的 React 应用程序,我不知道我在哪里做错了。

错误是:

“警告:遇到两个孩子用相同的钥匙,0。钥匙应该 是唯一的,以便组件在更新期间保持其身份。 非唯一键可能会导致子项重复和/或省略 — 该行为不受支持,可能会在未来版本中更改。 在 ul 在电影 (http://localhost:3000/static/js/main.chunk.js:1439:5) 在路线(http://localhost:3000/static/js/vendors~main.chunk.js:3780:29) 在 Switch (http://localhost:3000/static/js/vendors~main.chunk.js:3982:29) 在 div 在 div 在 div 在路由器 (http://localhost:3000/static/js/vendors~main.chunk.js:3411:30) 在 BrowserRouter (http://localhost:3000/static/js/vendors~main.chunk.js:3032:35) 在应用”

我的代码:

import React, {Component, Fragment} from "react";
import {Link} from 'react-router-dom';

export default class Movies extends Component {

    state = {
        movies: [],
        isLoaded: false,
        error: null,
    };

    componentDidMount() {
        fetch("http://localhost:4000/v1/movies")
          .then((response) => {
            console.log("Status code is", response.status);
            if (response.status !== "200") {
              let err = Error;
              err.message = "Invalid response code: " + response.status;
              this.setState({error: err});
            }
            return response.json();
          })
          .then((json) => {
            this.setState({
              movies: json.movies,
              isLoaded: true,
            },
            (error) => {
              this.setState({
                isLoaded: true,
                error
              });
            }
            );
        });
    }
    
    render() {
        const {movies, isLoaded, error} = this.state;
        
        if (error) {
            return <div>Error: {error.message}</div>
        } else if (!isLoaded) {
            return <p>Loading...</p>;
        } else {
         return (
            <Fragment>
                <h2>Choose a movie</h2>

                <ul>
                    {movies.map((m) => (
                        <li key={m.id}>
                           <Link to={`/movies/${m.id}`}>{m.title}</Link>
                        </li>
                    ))}
                </ul>
            </Fragment>
        );
        }
    }
}

【问题讨论】:

    标签: javascript reactjs react-router


    【解决方案1】:

    您可能有非唯一的电影 ID。

    React 使用组件键来确定集合中的哪些组件需要重新渲染,而不是每次发生任何变化时都重新渲染整个组件集。

    您可以在以下位置阅读有关密钥及其用途的更多信息 https://www.digitalocean.com/community/tutorials/react-react-keys-and-you

    可以使用索引作为键:

    {movies.map((m,i) => (
        <li key={i}>
           <Link to={`/movies/${m.id}`}>{m.title}</Link>
        </li>
     ))}
    

    以下是使用重复键和使用索引作为唯一键时的类似警告示例。 https://codesandbox.io/s/quiet-snowflake-26v1o?file=/src/App.js

    【讨论】:

    • WOOOOOOOOWWWW 谢谢!!!!
    • 您至少应该注意使用索引作为键的缺陷。来自docs“如果项目的顺序可能发生变化,我们不建议对键使用索引。这会对性能产生负面影响,并可能导致组件状态出现问题。请查看 Robin Pokorny 的 an in-depth explanation on the negative impacts of using an index as a key 文章。如果您选择不为列表项分配显式键,那么 React 将默认使用索引作为键。”
    猜你喜欢
    • 2021-11-27
    • 2014-01-09
    • 2017-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多