使用不同的键映射一个React组件

时间:2019-06-04 18:32:39

标签: reactjs dictionary ecmascript-6

我想加载组件,但是它显示了一个问题,即组件具有相同的键,但是我映射到selectedGroups上,并将gr.id作为键,使其在第一个版本发布之前就可以使用

sharingTabs = selectedGroups.map(gr => (
        <ExpansionPanel>
          <ExpansionPanelSummary expandIcon={<ExpandMoreIcon />}>
            <Typography className={classes.heading}>{gr.name}</Typography>
          </ExpansionPanelSummary>
          <ExpansionPanelDetails>
            <Grid container spacing={16}>
              <Grid item xs>
                <SharingSpacesTabs />
              </Grid>
            </Grid>
          </ExpansionPanelDetails>
        </ExpansionPanel>
      ));

但是后来我想将索引发送到props中,这就是为什么我在地图内添加了另一张地图的原因,这导致了回调函数的问题,并且我促成了return

sharingTabs = selectedGroups.map(function(gr) {
        const indexs = groups.map((group, index) => {
          if ((group.sharingspace.element = gr.id)) {
            return index;
          }
        });
        return (
          <ExpansionPanel key={gr.id}>
            <ExpansionPanelSummary expandIcon={<ExpandMoreIcon />}>
              <Typography className={classes.heading}>{gr.name}</Typography>
            </ExpansionPanelSummary>
            <ExpansionPanelDetails>
              <Grid container spacing={16}>
                <Grid item xs>
                  <SharingSpacesTabs id={gr.id} index={indexs[0]} />
                </Grid>
              </Grid>
            </ExpansionPanelDetails>
          </ExpansionPanel>
        );
      });

请帮助我找到我需要的解决方案,谢谢

2 个答案:

答案 0 :(得分:1)

我认为您的情况有问题,请更改您的功能条件以使用==或===正确检查相等性。

我也不知道如果不满足条件该怎么办,对于每个不满足条件的元素,map都将返回null。

 const indexs = groups.map((group, index) => {
          if ((group.sharingspace.element == gr.id)) {
            return index;
          }
        });

答案 1 :(得分:0)

最好的方法是传递第二个index作为map中的第二个参数,并使key={index}

 sharingTabs = selectedGroups.map((gr, index) => {
  const indexes = groups.map((group, index) => {
    if ((group.sharingspace.element = gr.id)) {
      return index;
    }
  });
  return (
    <ExpansionPanel key={index}>
      <ExpansionPanelSummary expandIcon={<ExpandMoreIcon />}>
        <Typography className={classes.heading}>{gr.name}</Typography>
      </ExpansionPanelSummary>
      <ExpansionPanelDetails>
        <Grid container spacing={16}>
          <Grid item xs>
            <SharingSpacesTabs id={gr.id} index={indexes[0]} />
          </Grid>
        </Grid>
      </ExpansionPanelDetails>
    </ExpansionPanel>
  );
});