保留react clone子循环内的数组索引

时间:2017-12-28 17:59:18

标签: javascript arrays reactjs loops closures

我有一个奇怪的问题,索引在循环和克隆时没有被保留 反应孩子。这是有问题的代码:

// Table Body component
const DataBody = ({
  resource,
  children,
  ids,
  data,
  ...rest
}) => (
  <tbody {...rest}>
    {ids.map((id, rowIndex) => (
      <TableRow key={id}>
        {React.Children.map(children, (field, index) => {
          return (
            <Cell
              key={`${id}-${field.props.source || index}`}
              record={data[id]}
              {...{ field, index, resource }}
            />
          )
        })}
      </TableRow>
    ))}
  </tbody>
)

// Table Cell component
const Cell = ({ classes, field, index, record, resource, theme, ...rest }) => {
  return (
    <td className={mapToCSSModule(classes, theme)} {...rest}>
      {React.cloneElement(field, { record, resource, index })}
    </td>
  )
}

// Table data component
const IndexField = ({
  format,
  index,
  tag: Tag = 'span',
  ...props
}) => {
  const no = index + 1
  return <Tag {...props}>{format ? format(no) : no}</Tag>
}

现在,问题是索引在IndexField中始终为0,但在Cell中它的值是正常的,就像我们在循环/闭包内丢失一样,它总是返回传递变量的最后一个值。 是否有一种干净的方式来优雅地处理这个?

编辑:添加了循环数据的主要组件,请注意这是流式传输版本(原始版本完全正常,只有非功能性的东西是索引)。

1 个答案:

答案 0 :(得分:0)

出于某种原因,rowIndex工作得很顺利,所以我实现了它而不是子索引..这里是代码:

// Table Body component
const DataBody = ({
  resource,
  children,
  ids,
  data,
  startingNo, // First item index (data is paged on the server)
  ...rest
}) => (
  <tbody {...rest}>
    {ids.map((id, rowIndex) => (
      <TableRow key={id}>
        {React.Children.map(children, (field, index) => {
          return (
            <Cell
              key={`${id}-${field.props.source || index}`}
              index={startingNo + rowIndex}
              {...{ field, resource }}
            />
          )
        })}
      </TableRow>
    ))}
  </tbody>
)