我正在调用一个 API 端点,将其数据保存到一个状态,然后渲染它。它显示在浏览器中,但控制台上有警告:Warning: Each child in a list should have a unique "key" prop.
.
My app.js
:
class App extends Component {
render () {
return (
<div>
<Profile profiles={this.state.profile} />
</div>
)
}
state = {
profile: []
};
componentDidMount() {
fetch('http://127.0.0.1:8000/profiles')
.then(res => res.json())
.then((data) => {
this.setState({ profile : data })
})
.catch(console.log)
}
}
export default App;
我不明白我该把它放在哪里key prop在渲染()中。这是我的片段profile.js
:
const Profile = ({ profiles }) => {
return (
<div>
<center><h1>Profiles List</h1></center>
{profiles.map((profile) => (
<div className="card">
<div className="card-body">
<h5 className="card-title">{profile.first_name} {profile.last_name}</h5>
<h6 className="card-subtitle mb-2 text-muted">{profile.dob}</h6>
<p className="card-text">{profile.sex}</p>
</div>
</div>
))};
</div>
)
};
export default Profile;
key prop 相比不使用它带来了哪些改进?我对这些感到不知所措<div>...</div>
tags.
如果你使用map
在你的 JSX 返回中,你需要为父元素提供key
prop 以便它被唯一标识。
https://reactjs.org/docs/lists-and-keys.html https://reactjs.org/docs/lists-and-keys.html
您最好使用对象 ID,但如果您知道构成唯一键的字段(或字段组合),那么您可以使用它:
{profiles.map((profile) => (
<div
key={'profileList_'+profile.first_name+profile.last_name}
className="card"
>
...
</div>
)};
注意:在我使用的示例中profileList_
作为前缀,以防万一您需要使用相同的唯一标识符(对象 ID 或在本例中profile.list_name+profile.last_name
)作为不同上下文中其他地方的键。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)