我正在调用API端点,将其数据保存到一个状态,然后呈现它。它显示在浏览器中,但控制台上显示警告:Warning: Each child in a list should have a unique "key" prop.
。
我的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放在render()中的什么位置。这是我的代码段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;
关键道具带来了哪些改进而不使用它?这些<div>...</div>
标签让我不知所措。
您必须将uniq值设置为地图中第一个div的key
道具
{profiles.map((profile) => (
<div key={profile.id} className="card">
读取doc
如果在JSX返回中使用map
,则需要为父元素提供key
道具,以便对其进行唯一标识。
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
)作为键。