简体   繁体   English

用地图打印反应组件内的数字?

[英]Print numbers inside react component with map?

This is probably an easy one, but I can't seem to figure it out.这可能很容易,但我似乎无法弄清楚。 How do I print the numbers in order inside my list?如何在列表中按顺序打印数字? If I print index some of the numbers will be skipped due to my conditions?如果我打印索引,由于我的条件,某些数字会被跳过吗? Can I set a count++ somewhere inside my map-function inside my condition so it will increase every time a list-item is printed?我可以在我的条件中的地图函数中的某处设置一个 count++ 以便每次打印列表项时它都会增加吗?

export const MFAPaging = ({rootStore, page}) => {
  let count = 1;

  return (
    <div className="components-paging-brder">
      <div className="components-paging">
        <ul>
          {rootStore.mfaStore.links.map((item, index) =>
              item && item.includePage ? 
              <li className={page == index ? 'active' : ''} key={index}>{count}</li>
              : undefined 
            )}
        </ul>
        <MFAButtons rootStore={rootStore} page={page} />
    </div>
  </div>
  );
};

First you can filter the array, and then your indexes will be cool in your .map (never use .map to filter, you already have build-in functions)首先你可以过滤数组,然后你的索引在你的 .map 中会很酷(永远不要使用 .map 来过滤,你已经有了内置函数)

{rootStore.mfaStore.links.filter((item)=> item && item.includePage).map((item, index) =>
    <li className={page == index ? 'active' : ''} key={index}>{count}</li>
)}

For questions comment :)对于问题评论:)

You have to increment the count variable on each iteration.您必须在每次迭代时增加计数变量。 You can try the following.您可以尝试以下操作。 It should solve your problem.它应该可以解决您的问题。

<li className={page == index ? 'active' : ''} key={index}>{count++}</li>

++ at the end is important. ++结尾很重要。 count++ will first read the current count variable's value then increment its value. count++将首先读取当前count变量的值,然后增加其值。

Try to use foreach, because if u try to use map, your result will be like a array with some undefined values: [<li></li>, undefined, <li></li>] , and foreach prevent it.尝试使用 foreach,因为如果你尝试使用 map,你的结果将像一个包含一些未定义值的数组: [<li></li>, undefined, <li></li>] ,而 foreach 会阻止它。

const renderList = ({fullList}) => {
  let counter = 0;
  const renderList = [];
  list.foreach((data, index) => {
    if (data && data.includePage) renderList.push(<li>{++counter}</li>);
  });
  return renderList;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM