3

这可能是一个简单的,但我似乎无法弄清楚。如何在我的列表中按顺序打印数字?如果我打印索引,由于我的条件,一些数字会被跳过?我可以在我的条件内我的地图函数内的某个地方设置一个 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>
  );
};
4

3 回答 3

3

首先你可以过滤数组,然后你的索引会在你的 .map 中很酷(永远不要使用 .map 过滤,你已经有内置函数)

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

对于问题评论:)

于 2019-11-28T14:55:05.443 回答
0

您必须在每次迭代时增加计数变量。您可以尝试以下方法。它应该可以解决您的问题。

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

++最后很重要。count++将首先读取当前count变量的值,然后增加其值。

于 2019-11-28T15:08:12.797 回答
0

尝试使用 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;
}
于 2019-11-28T15:11:33.097 回答