英文:
Reactjs Two children with the same key react
问题
当我尝试查看另一个用户的个人资料时,出现了以下错误:“警告:遇到具有相同键的两个子元素,用户ID在此处
。键应该是唯一的,以便组件在更新时保持其标识。非唯一的键可能会导致子元素被复制和/或被省略 - 这种行为是不受支持的,可能会在将来的版本中更改。”
我尝试了索引,但没有奏效,我还尝试了ID号码,也没有奏效。
我感到绝望。
这是我的代码:
<div className='ProfileInfo'>
{userData.length > 0 && userData.map(((user, index) => (
<div className='profileInfo-container' key={index}>
<div className='profileInfo-top'>
</div>
<div className='profileInfo-center'>
<img className='profile-avatar' fontSize="large" src={auth.user.avatar} alt="" />
{user._id && auth && user._id === auth.user._id ?
<button className='addfbtn' onClick={() => setEdit(true)}>编辑个人资料</button>
: <GlobalFriendBtn classBtn="addfbtn" user={user}/>
}
</div>
{/* ... 等等 */}
</div>
)))}
</div>
查看这里的问题截图:
https://www11.0zz0.com/2023/06/19/07/487328533.png
<details>
<summary>英文:</summary>
when am trying to Profile info of another user it shows duplicate with this error
"Warning: Encountered two children with the same key, `the id of user here`. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version."
I tried the index, and it didn't work, and I tried the ID number, and it didn't work either.
I'm despaired
this is my code
<div className='ProfileInfo'>
{userData.length > 0 && userData.map(((user, index) => (
<div className='profileInfo-container' key={index} >
<div className='profileInfo-top'>
</div>
<div className='profileInfo-center'>
<img className='profile-avatar' fontSize="large" src={auth.user.avatar} alt=""/>
{user._id && auth && user._id === auth.user._id ?
<button className='addfbtn' onClick={()=>setEdit(true)}>EDIT PROFILE</button>
: <GlobalFriendBtn classBtn="addfbtn" user={user}/>
}
</div> ... etc،
look at this:
https://www11.0zz0.com/2023/06/19/07/487328533.png
</details>
# 答案1
**得分**: 3
这应该可以工作,如果每个用户都有唯一的ID。
```jsx
<div className='ProfileInfo'>
{userData.map(user => (
<div className='profileInfo-container' key={user._id}>
...
</div>
))}
</div>
可能会发生多个用户具有undefined
或类似的ID,并引发错误。
另一个注意事项:您不需要检查数组的长度,userData.map
如果数组为空,将什么都不渲染。
英文:
This should work if each user has unique id.
<div className='ProfileInfo'>
{userData.map(user => (
<div className='profileInfo-container' key={user._id}>
...
</div>
))}
</div>
It might happen that multiple user has undefined
or similar id, and that causes the error.
Another note: you do not need to check the length of the array, userData.map
will simply render nothing if the array is empty.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论