我正在尝试仅提取JSON文件(ID为1-10)中的前10个条目。寻找下面的代码是否可行以及最好的方法是什么。我希望控制显示到前10个结果中的数量,并添加一个按钮以加载更多10个结果(ID为11-20等)
这是我提取结果的方式:
import React, { Component } from 'react'
import PostData from '../data/posts.json'
class PostList extends Component {
render () {
return (
<div>
<h1>Welcome</h1>
{PostData.map((postDetail, index) => {
return <h2>{postDetailDetail.title}</h2>
})}
</div>
)
}
}
这是posts.json文件的快照(不完整):
[
{
"id": 1,
"title": "Hello World",
"content": "content goes here",
},
{
"id": 2,
"title": "Hello React",
"content": "another content goes here",
},
// ...continued entries. Cut off to save space.
]
你可以这样
{PostData.map((postDetail, index) => {
return index <= 9 ? <h2>{postDetailDetail.title}</h2> : undefined
})}
仅在索引小于或等于9时返回html(这是从10开始的第十个位置)
这是带有增加按钮的完整示例
import React, { Component } from 'react'
import PostData from '../data/posts.json'
class PostList extends Component {
state = {showCount: 10}
render () {
return (
<div>
<h1>Welcome</h1>
{PostData.map((postDetail, index) => {
return index + 1 <= showCount ? <h2>{postDetailDetail.title}</h2> : undefined
})}
<button
onClick={() => this.setState(prevState => {
showCount: prevState.showCount + 10
})}>
Increase show count</button>
</div>
)
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句