首先,我想承认这是我对 React 的尝试,我正在尝试学习如何使用这个库。
我想尝试从我的一个 API 中创建一些图像的无限滚动。
我已将react-infinite-scroll-component
and '@material-ui` 添加到我的项目中。
这是我的ImageGallery
组件当前的样子:
import React from "react";
import Card from '@material-ui/core/Card';
import CardHeader from '@material-ui/core/CardHeader';
import CardActions from '@material-ui/core/CardActions';
import Avatar from '@material-ui/core/Avatar';
import IconButton from '@material-ui/core/IconButton';
import FavoriteIcon from '@material-ui/icons/Favorite';
import CommentIcon from '@material-ui/icons/ModeComment';
import Grid from "@material-ui/core/Grid";
import InfiniteScroll from 'react-infinite-scroll-component';
import Images from "./Images";
class ImageGallery extends React.Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
more: false,
images: [],
page: 0
}
}
componentDidMount() {
this.loadMore(this.state.page);
}
loadMore(page) {
fetch('https://localhost/api/feed.php?type=1&start=' + this.state.page)
.then(res => res.json())
.then(
(result) => {
this.setState({
isLoaded: true,
images: result.images,
more: true,
page: page++
});
},
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
}
render() {
return (
<Grid container spacing={2}>
<InfiniteScroll
dataLength={ this.state.images.length }
hasMore={ this.state.more }
next={ this.loadMore( this.state.page ) }
height={'100%'}
loader={ <div>Loading...</div> }
>
{this.state.images.map(item => (
<Grid container item xs={6} sm={3} md={2} key={item.ID}>
<Card variant="outlined" square style={{width: '100%'}}>
<CardHeader
avatar={
<Avatar alt={item.username} src={item.profileIMG} />
}
title={item.username}
subheader={item.timeAgo}
/>
<Images src={item.imageURL} alt={item.username} />
<CardActions disableSpacing>
<IconButton>
<FavoriteIcon />
</IconButton>
<IconButton>
<CommentIcon />
</IconButton>
</CardActions>
</Card>
</Grid>
))}
</InfiniteScroll>
</Grid>
);
}
}
export default ImageGallery;
当我尝试运行该应用程序时,它会无限地反复调用 API,并且不会更改页码。此外,InfiniteScroll 组件似乎在网格内部存在一些问题,因为该元素没有填充父容器的宽度。
关于我的代码可能出错的地方或我应该在哪里进行一些更改的任何想法?