如何从lodash _.times返回多个值?

时间:2019-09-09 17:39:36

标签: reactjs lodash

由于某种原因,我的lodash方法_.times无法正常工作。即使我在col方法中给了它,它也不会为我正在调用的其他函数提供_.times的值。

// shownNews is a data-table, pulled from the database. 

return (
  <>
    <AddNews/>
    {_.times(shownNews.length, (col) =>
      <Info
        key={col}
        shownNews={shownNews}
        col={shownNews.length - 1 - col}
      />,
      <ReadMore
        shownNews={shownNews}
        col={col} // this gives me an error, col not found
      />
    )}
  </>
);

关于如何解决此问题的任何想法?

1 个答案:

答案 0 :(得分:1)

在官方文档中,提到_.times在第二个参数中接受一个函数。而在您的情况下,您要传递3个参数。

我在REPL(复制您的方案)中尝试了以下操作:

_.times(3, (index) => JSON.stringify(index*2), JSON.stringify(index*3));

我得到了错误:第三个参数ReferenceError: index is not defined

目前尚不清楚您要达到的目标,但是否愿意 InfoReadMore一起使用,如下所示使用Fragment

{_.times(shownNews.length, (col) =>
  <Fragment key={col}>
    <Info
      shownNews={shownNews}
      col={shownNews.length - 1 - col}
    />
    <ReadMore
      shownNews={shownNews}
      col={col} // this gives me an error, col not found
    />
  </Fragment>
)}

或者如果您想分别使用InfoReadMore,请使用_.times 2次。