首页 > 解决方案 > 在 React 中映射数组时仅获取最后一项的数据

问题描述

有两个项目 - 第一个的 ID = 69,第二个的 ID 为 70。函数renderToolTipButtons接收按钮列表并呈现(示例如下)。我面临的问题是页面呈现时,第6 行控制台上项目 ID 的数据正确显示为 69,然后是 70。但是当我实际单击渲染按钮时,第 14 行仅显示第二个项目的项目 ID,即总是70 ...我相信这与关闭有关?

任何帮助将不胜感激 :)

   return [
      {
        text: 'Button 1',
        icon: <EditIcon fontSize="small" />,
        color: '#272727',
        callback: handleEditProject,
      },
      {
        text: 'Button 2',
        icon: <DeleteIcon fontSize="small" />,
        color: '#c12026',
        callback: handleLeaveProject,
      },
    ];
export default function CustomToolTip(props) {
  const { open, anchorEl, index, tooltipButtons, projectID } = props;

  const renderTooltipButtons = buttons => {
    return buttons.map((button, index) => {
      console.log(projectID); // LINE 6 **  This console log shows 69 and 70 when the components render **

      return (
        <React.Fragment key={index}>
          <Button
            onClick={event => {
              event.stopPropagation();
              // button.callback(projectID) -> The goal is to call something like this, but projectID always refers to the last project ID, 70. 
              console.log(projectID); // LINE 14 **** Always the ID of the last item, which is 70 upon clicked ****
            }}
            startIcon={button.icon}
          >
            <span style={{ color: button.color }}>{button.text}</span>
          </Button>
        </React.Fragment>
      );
    });
  };

  return (
    <Popper
      modifiers={{
        preventOverflow: {
          enabled: false,
          boundariesElement: 'viewport',
        },
      }}
      id={index}
      placement="bottom-end"
      open={open}
      anchorEl={anchorEl}
    >
      <Paper elevation={0}>{renderTooltipButtons(tooltipButtons)}</Paper>
    </Popper>
  );
}

标签: reactjsclosures

解决方案


推荐阅读