我有一个从DB JSON获取JSON数据的应用程序,并且我希望对数据进行分页,例如每页显示1张图像的示例。我该怎么做?这是我的数据库JSON
db.json文件:
"interiores": [
{
"images": [
"img_01", "img_02", "img_03", "img_04", "img_05"
]
}
]
我有一个React组件代码,可以通过axios来获取JSON数据。运行正常。
反应组件文件:
import React, { Component } from 'react'
import axios from 'axios'
const URL_INTERIORES = 'http://localhost:3001/interiores';
class Interiores extends Component {
constructor(props) {
super(props)
this.state = {
interiores: [],
}
}
componentDidMount() {
axios.get(URL_INTERIORES)
.then(res => {
this.setState({ interiores: res.data })
})
}
render() {
return (
<div>
{this.state.interiores.map(item =>
<div>
<div className="gallery images-box-1">
{
item.images
.map((img) => {
return (
<a href={`../images/${img}.jpg`}>
<img src={`../images/${img}_thumb.jpg`} alt="" />
</a>
)
})
}
</div>
</div>
)}
</div>
);
}
}
export default Interiores;
SO用户 the code 的Piotr Berebecki可以为您提供帮助。该代码成功运行。它是从简单数组返回项目的分页。我想做同样的事情,但是从上面显示的JSON DB返回数据。我能怎么做?我该如何解决?谢谢。
答案 0 :(得分:0)
如果您已经使用create-react-app来搭建项目,则可以直接导入json文件,然后从中读取内容,该模块已经包含在内,您只需导入json即可,否则可以安装json-loader moudule 。 有关更多详细信息,您可以参考此答案。 es6 modules implementation, how to load a json file
对于分页状态,您可以在页面底部进行类似的操作
images.map((img) => { <li onClick={(img)=> this.updateImage(img)}> img.id</li>})
使更新处理程序类似
updateImage(img) {
this.setState({
currentImg: img
})
}
然后您可以在状态下使用currentImg来显示渲染方法。