所以我正在学习react和js,我试图每20次循环一次(单页的限制)并显示这些图片,也显示在底部这个页面索引使用bootstrap。但它并没有真正工作,这是我的代码:
const pictureItems = this.state.imgFiles.map((img, index) => {
return (
<PictureListItem
id={index}
key={`img-${img.name}`}
imgFile={img}
pictureDataUpdate={this.onUpdatePicture}
/>
);
});
const pageNumber = this.state.imgFiles.length / 20;
let pages = "";
for (let i = 0; i < pageNumber; i++) {
pages += <li><a>{i}</a></li>;
return pages;
}
我在想也许我可以把索引的值传递给循环,并在开始时乘以20,然后在结束时加上20。但是我甚至不能让页面显示好
protip:不要自己做语言自己已经做的事情。
const picturesPerPage = 20;
const images = this.state.imgFiles;
...
// get the current page, rounded down. We don't want fractions
let currentPageNumber = (images.length / picturesPerPage)|0;
// find the start and end position in the "images" array for this page
let start = currentPageNumber * picturesPerPage;
let end = (1+currentPageNumber) * picturesPerPage;
// cool: make JS get those items for us, and then map those items to bits of JSX
let pages = images.slice(start, end).map(img => {
return (
<li key={img.src}>
<a href={img.href}>
<img src={img.src} alt={img.alt}/>
</a>
</li>
);
});
// and we're done.
return <ul>{ pages }</ul>;
请注意,如果你正在构建一个动态React元素的数组,他们需要有一个key
属性,以便React diff引擎可以正确地完成它的工作-键需要唯一地标识实际的东西,所以你不能使用数组位置(['a','b']和['b','a']是相同的数组,但如果你假装数组位置是键,而不是"只是交换两个元素",你是在撒谎从一个到另一个发生了什么。声称发生了实际的内容更改,而实际上并没有,事情变得非常低效)。
还请注意,您试图使用+=
向数组中添加元素-这是非法语法,+=
是字符串连接。要将单个元素添加到数组中,您可以使用array.push
(或者如果您需要一些奇怪的东西,可以使用array.splice
)