React:列表中的每个子项都应该在reactapp中具有唯一的“key”道具错误

问题描述 投票:0回答:2

我使用此代码列出帖子


const PostList = () => {
  const [posts, setPosts] = useState({});

  const fetchPosts = async () => {
    const res = await axios.get("http://localhost:4002/posts");

    setPosts(res.data);
  };

  useEffect(() => {
    fetchPosts();
  }, []);

  const renderedPosts = Object.values(posts).map((post) => {
    return (
      <div
        className="card"
        style={{ width: "30%", marginBottom: "20px" }}
        key={post.id}
      >
        <div className="card-body" key={post.id}>
          <h3>{post.title}</h3>
          <CommentList comments={post.comments} />
          <CommentCreate postId={post.id} />
        </div>
      </div>
    );
  });

  return (
    <div className="d-flex flex-row flex-wrap justify-content-between">
      {renderedPosts}
    </div>
  );
};

export default PostList;

但我收到错误

警告:列表中的每个子项都应该有一个唯一的“key”道具。

检查

PostList
的渲染方法。请参阅 https://reactjs.org/link/warning-keys 了解更多信息。 在div 在 PostList (http://localhost:3000/static/js/bundle.js:441:76) 在div 在应用程序

请帮忙

reactjs
2个回答
1
投票

以这种方式渲染组件。

const PostList = () => {
  const [posts, setPosts] = useState({});

  const fetchPosts = async () => {
    const res = await axios.get("http://localhost:4002/posts");
    setPosts(res.data);
  };

  useEffect(() => {
    fetchPosts();
  }, []);


  return (
    <div className="d-flex flex-row flex-wrap justify-content-between">
      {posts.map((post) => (
      <div
        className="card"
        style={{ width: "30%", marginBottom: "20px" }}
        key={post.id}
      >
        <div className="card-body">
          <h3>{post.title}</h3>
          <CommentList comments={post.comments} />
          <CommentCreate postId={post.id} />
        </div>
      </div>
    ))}
    </div>
  );
};

export default PostList;

-1
投票

您需要为每个渲染元素提供唯一的键。处理此警告的最简单方法是:

const renderedPosts = Object.values(posts).map((post, index) => {
return (
  <div
    className="card"
    style={{ width: "30%", marginBottom: "20px" }}
    key={index}
  >
    <div className="card-body" key={post.id}>
      <h3>{post.title}</h3>
      <CommentList comments={post.comments} />
      <CommentCreate postId={post.id} />
    </div>
  </div>
);

});

还要检查您正在映射的帖子对象。也许存在具有相同键的元素。

© www.soinside.com 2019 - 2024. All rights reserved.