React 警告:列表中的每个子项都应该有一个唯一的“key”道具。在 render() 函数中

for*_*est 3 javascript reactjs

我正在调用一个 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;
Run Code Online (Sandbox Code Playgroud)

我不明白将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;
Run Code Online (Sandbox Code Playgroud)

key prop 相比不使用它带来了哪些改进?我对这些标签感到不知所措<div>...</div>

bil*_*wit 5

如果您在 JSX 返回中使用map,则需要为父元素提供 prop,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>
)};
Run Code Online (Sandbox Code Playgroud)

注意:在示例中,我用作profileList_前缀,以防万一您需要profile.list_name+profile.last_name在不同上下文中的其他位置使用相同的唯一标识符(对象 ID 或在本例中)作为键。

  • 前缀是无用的,因为“key”仅在其同级之间相关。如果没有提供,React 默认会回退到索引。 (2认同)
  • @BhaskarS。我假设你的对象中可能不存在“id”属性 (2认同)