【问题标题】:how to loop every 20 positions in a array如何循环数组中的每 20 个位置
【发布时间】:2016-10-21 16:47:18
【问题描述】:

所以我正在学习 react 和 js,并且我尝试每 20 次循环(单个页面中的限制)并显示此图片,还使用引导程序在此页面索引的底部显示。但它并没有真正起作用这是我的代码:

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 添加到结束。但我什至无法让页面很好地显示。

【问题讨论】:

标签: javascript loops reactjs render


【解决方案1】:

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 差异引擎可以正确地完成它的工作 - 关键需要唯一地标识实际事情,所以你不能使用数组位置(['a','b']和['b','a']是同一个数组,但是如果你假装数组位置是一个键,而不是“只是交换这两个元素”你在谎称从一个元素到另一个元素会发生什么,声称实际的内容更改发生了,而实际上它们没有发生,事情变得非常低效)。

还请注意,您尝试使用 += 将元素添加到数组中 - 这是非法语法,+= 是字符串连接。要将单个元素添加到数组中,请使用 array.push(或者如果您需要一些奇怪的东西,array.splice

【讨论】:

  • 你有太多的代表来回答一个明显的骗局。
  • 相反:我有足够多的代表知道我可以回答这个问题,只要写下文字,不要让我背上皮肤,并帮助显然现在的人需要帮助。告诉他们“以前有人问过这个问题”是有效打击某人诚实尝试学习新事物的好方法。他们努力用代码提出了一个很好的问题,这对于首次发帖者来说极为罕见,因此这种努力值得以实物的形式回应。问一个好问题,得到一个答案。问一个不好的,得到一个“重复关闭”。
  • 你有足够的代表知道作为重复关闭不是一件坏事"Duplicate questions are not necessarily bad; different descriptions of the same problem help future visitors to find the answers they're looking for."。他们将得到答案并学习“新事物”。诚然,这意味着回答者通过回答已经回答的问题来获得更多代表的机会更少,但从长远来看,这对访问者来说更好。
猜你喜欢
  • 1970-01-01
  • 2022-11-01
  • 1970-01-01
  • 2012-08-07
  • 2018-03-28
  • 2011-12-18
  • 1970-01-01
  • 1970-01-01
  • 2019-12-27
相关资源
最近更新 更多