[英]select items from array with splice using a loop
我使用的是方阵。 我确实设法从数组中获取数据,但是数据包含20张随机图片。 我只希望在我的网站上看到3张图片。
我已经使用了切片数组。 不幸的是,这对我不起作用,我认为我做错了什么。 -> 在for循环中使用拼接从数组中删除项目,也许我应该使用if函数?
这是我的代码:
{apiImages.map( img => (
<Card shadow={5} style={{minWidth: '450', margin: 'auto'}}>
<a href="/alleblogs">
<CardTitle style={{color: '#fff', height: '176px', background: 'url( { } ) center / cover' }}>Golden Bridge</CardTitle>
<CardText>
Lorem ipsum, dolor sit amet consectetur adipisicing elit. Facilis distinctio esse qui eos, ad provident,
</CardText>
<CardActions border>
<Button style={{color: '#8dd5e8'}}>Likes:</Button>
<Button style={{color: '#8dd5e8'}}>Share</Button>
</CardActions>
</a></Card>
))}
如您所见,我使用了循环。 此循环仅显示20张卡片(无图片),但是我的问题是我只希望显示3张卡片。
{apiImages.splice(6).map( img => ---> This doesn't work either.
我不知道,但也许这段代码也会有用(这是我获取api的地方):
componentDidMount() {
fetch("https://pixabay.com/api/?key=11095386-871fd43c33a92700d9bffb82d&q=travel&image_type=photo&pretty=true")
.then(res => res.json())
.then(
(result) => {
console.log(result)
this.setState({
apiImg: result.hits
});
},
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
}
您可以使用Array.slice
直接切片数组。
var a = [1,2,3,4,5,6,7,22,34,43,56] a.slice(0, 3).map((v) => { console.log('Element:', v) })
{apiImages.slice(0, 3).map( img => ---> This will work.
我建议使用不修改初始数组apiImages
slice
方法:
// create a const that store first 3 images
const firstThreeImages = apiImages.slice(0, 3);
// render them
{firstThreeImages.map(img => //rendering )}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.