1

我正在 NextJS 中学习 getStaticProps。我正在使用https://jsonplaceholder.typicode.com/posts API 在页面上呈现帖子。以下是我的 JS 文件代码:

function PostList({posts}){
    return (
        <>
        <h1>
            List of posts
        </h1>
        {
            posts.map(post => {
                return (
                <>
                    <div key={post.id}>
                        <h2>{post.id} {post.title}</h2>
                    </div>
                    <hr/>
                </>    
                    
                )
            })
        }
        </>
        )

}

export async function getStaticProps(){
    const response = await fetch('https://jsonplaceholder.typicode.com/posts')
    const data = await response.json()
    return {
        props: {
            posts: data
        }
    }
}

export default PostList

但是,控制台给了我以下错误:

react_devtools_backend.js:4045 Warning: Each child in a list should have a unique "key" prop.

我将每个帖子的 ID 分配为“div”标签中的键。但是,我仍然收到错误消息。我的代码有问题还是我应该添加其他内容?

4

2 回答 2

1

而不是 <></> 使用下面的 Fragment 形式,它允许设置密钥。

<React.Fragment key={item.id}>... </React.Fragment>

以供参考

于 2021-12-25T19:37:54.860 回答
0

您只需key在地图内围绕 dom 节点的标签添加一个属性。

function PostList({posts}){
    return (
        <>
        <h1>
            List of posts
        </h1>
        {
            posts.map(post => {
                return (
                    <div key={post.id}>
                        <h2>{post.id} {post.title}</h2>
                    <hr/>
                    </div>  
                )
            })
        }
        </div>
        )

}

于 2021-12-25T18:25:07.817 回答