【问题标题】:Why the index is always the last index when using it to pass to function while map over an array?为什么在映射数组时使用它传递给函数时索引总是最后一个索引?
【发布时间】:2019-05-15 13:43:49
【问题描述】:

我正在使用 map 循环从服务器获取的数组对象,每个对象用于表中的一行来显示数据。我想通过调用函数并传递给索引对每一行执行特定操作。 这里的代码:

       <TableBody>
          {productsData.map((product, index) => {
            return (
              <TableRow key={product.productId}>
                <TableCell>
                  <Button
                    aria-owns={anchorEl ? `manipulation${index}` : undefined}
                    aria-haspopup="true"
                    onClick={handleClick}
                    className={classes.button}
                    size="small"
                    variant="contained"
                  >
                    Thao tác
                  </Button>
                  <Menu id={`manipulation${index}`} anchorEl={anchorEl} open={Boolean(anchorEl)} onClose={handleClose}>
                    <MenuItem onClick={**handleOpen(index)**}>Xem trước</MenuItem>
                  </Menu>
                </TableCell>
              </TableRow>
             )
           })}
        </TableBody>

我声明handleOpen的方式:const handleOpen = (index) =&gt; () =&gt; {...} =>我预计handleOpen会像这样呈现:第0行的handleOpen(0),第1行的handleOpen(1)。但它总是以数组的最后一个索引结束。可能是关于javascript中的关闭,但我不知道如何修复

请给我任何建议。提前致谢。

【问题讨论】:

标签: javascript reactjs loops material-ui


【解决方案1】:

您所做的方式将在渲染后立即调用 handleOpen 函数,而不是像您希望的那样仅在单击时调用它。

要解决此问题,请使用匿名函数:

&lt;MenuItem onClick={() =&gt; handleOpen(index)}&gt;

这将创建一个仅在实际点击 MenuItem 组件时调用的函数。

【讨论】:

  • 对不起,我忘了提到我是如何定义handleOpen函数的。
  • const handleOpen = index => () => {..}。兄弟,你的方式也一样。
  • 不是这样,因为你只是用最后一个索引覆盖了 handleOpen 函数,所以每次点击你都会调用用最后一个索引构造的函数。
  • 我尝试了你的方法,但仍然卡住了。有点奇怪。我曾经遇到过同样的情况,以我的方式,它工作得很好,但现在我真的不知道会发生什么
  • 也是一样的,他的handleOpen是返回一个函数,这个函数返回一个函数,这个函数会捕获索引。所以它应该工作。我建议 OP 创建一个简单的 sn-p / codebin 等...
猜你喜欢
  • 2022-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-09
  • 2021-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多