gpt4 book ai didi

javascript - 理解 react Prop 和键

转载 作者:行者123 更新时间:2023-12-04 09:51:52 26 4
gpt4 key购买 nike

在这里 react 新手。我指的是this并遵循遍历 react 视频,我已经使用 bootstrap4.5 自定义了我的应用程序。我知道必须传递唯一键才能提高性能并帮助 React 识别更改的项目。
我有 Users.js

1  const Users = (props) => {
2 //class changed to arrow functions
3 if (props.loading) {
4 return <Spinner />
5 }
6 else {
7 return (
8 <div className="row">
9 {props.users.map((user) => (
10 <div className="col-sm-3 mt-3" >
11 <UserItem key={user.id} user={user} />
12 </div>
13 ))}
14 </div >
15 );
16 }
17 }

在上面的代码中,我在下面的控制台中收到错误:
Warning: Each child in a list should have a unique "key" prop. Check the render method of `Users`. See https://reactjs.org/docs/lists-and-keys.html#keys for more information.

如果我像下面那样更改第 10 行和第 11 行,则错误不再存在
10                    <div key={user.id} className="col-sm-3 mt-3"  >
11 <UserItem user={user} />

这背后的原因是什么,因为它有效,所以可以像这样传递 key 吗?

列表如下所示,在 props 中传递
[
{
"login": "mojombo",
"id": 17,
"avatar_url": "https://avatars0.githubusercontent.com/u/1?v=4",
"url": "https://api.github.com/users/mojombo",
"html_url": "https://github.com/mojombo"
},
{
"login": "wintersword",
"id": 18,
"avatar_url": "https://avatars0.githubusercontent.com/u/1?v=4",
"url": "https://api.github.com/users/mojombo",
"html_url": "https://github.com/mojombo"
}
]

react 版本:“16.13.1”

最佳答案

改变,

{props.users.map((user) => (
<div className="col-sm-3 mt-3" >
<UserItem key={user.id} user={user} />
</div>
))}


{props.users.map((user) => (
<div className="col-sm-3 mt-3" key={user.id}>
<UserItem user={user} />
</div>
))}

这里 key={user.id}需要在 div element 是 map 的直接父元素方法..

-> The key prop has to be in the parent element under map method which refers to all the sibilings..

-> Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity and it needs to be in immediate parent element.

-> The outermost/parent element returned by the map function needs to have a key prop with unique value.



在您的代码中,

父元素:
<div className="col-sm-3 mt-3" key={user.id}>

sibling ,
<UserItem key={user.id} user={user} />

所以父元素需要在关键属性中使用唯一值来标识..

关于javascript - 理解 react Prop 和键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62003443/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com