谁能解释为什么我会收到有关"same key"的错误



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

错误为:

"警告:遇到两个具有相同密钥0的子级。钥匙应该是唯一的,以便组件在更新过程中保持其身份。非唯一密钥可能导致子项被复制和/或省略--该行为不受支持,并且可能在将来的版本中更改。在ul在电影(http://localhost:3000/static/js/main.chunk.js:1439:5)在Route(http://localhost:3000/static/js/vendors~main.cochunk.js:3780:29(在交换机(http://localhost:3000/static/js/vendors~main.cochunk.js:3982:29(在div在div在div在路由器(http://localhost:3000/static/js/vendors~main.cochunk.js:3411:30(在BrowserRouter(http://localhost:3000/static/js/vendors~main.cochunk.js:3032:35(在App"上;

我的代码:

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>
);
}
}
}

您可能有非唯一的电影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

相关内容

最新更新