【问题标题】:React Error: Each child in a list should have a unique key prop反应错误:列表中的每个孩子都应该有一个唯一的关键道具
【发布时间】:2019-11-17 22:38:28
【问题描述】:

以下有什么问题:

<List>
  {sections.map(section => (
    <>
      {section.header && <ListSubheader key={section.header}>{section.header}</ListSubheader>}
      {section.items
        .filter(item => new RegExp(itemsFilter, 'i').test(item.value))
        .map(item => {
          const labelId = `multi-select-filter-list-checkbox-label-${item.key}`;
          return (
            <ListItem key={item.key} role={undefined} dense button onClick={handleToggle(item)}>
              <ListItemIcon>
                <Checkbox
                  className={checkboxClasses.root}
                  edge="start"
                  checked={checked.indexOf(item) !== -1}
                  tabIndex={-1}
                  disableRipple
                  color="primary"
                  inputProps={{ 'aria-labelledby': labelId }}
                />
              </ListItemIcon>
              <ListItemText
                id={labelId}
                primary={item.value}
                primaryTypographyProps={{
                  variant: 'body1'
                }}
              />
            </ListItem>
          );
        })
      }
    </>
  ))}
</List>

我相信我正在提供钥匙;错误在哪里?

【问题讨论】:

  • 您的物品中有重复的钥匙吗?

标签: reactjs material-ui


【解决方案1】:

应该为包装标签提供key 属性。

&lt;&gt; 替换为&lt;React.Fragment&gt; 并为其应用密钥。

<React.Fragment key={section.header}>

【讨论】:

    【解决方案2】:

    正如kind-user 用户所说,您应该将密钥添加到包装标签。 键是唯一可以传递给的属性。

    注意:当你向 传递一个键时,你不能使用这个简写。 而是使用

    <React.Fragment key={yourKey}> 
    ... 
    <React.Fragment>
    

    【讨论】:

      猜你喜欢
      • 2021-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-16
      • 2019-12-11
      • 2020-03-30
      • 2020-08-10
      • 1970-01-01
      相关资源
      最近更新 更多