首页 > 解决方案 > MUI 中的键不是强制性的吗?

问题描述

我目前正在使用 Typescript (3.5.1)、React (16.8.6)、Material-Ui (v4) 和 CRA 制作菜单。我正在使用List来自material-ui的。我忘记key在我的上添加一个,ListItems并且在开发工具中没有警告。

我认为在列表项中强烈推荐键?当我没有为 a 提供密钥时,我已经在其他组件中收到了警告,ListItem因此我尝试运行一些测试。

// This code shows no warning when rendered, even if no key
// was provided to the ListItem

render(){
  return(
    <List>
    {  [
        {text: 'files', icon: <FolderIcon />, path: '/my-files/'},
        {text: 'shared files', icon: <SharedIcon />, path: '/shared-files'},
      ].map(item => (
               <ListItem button>
                 <ListItemIcon>{item.icon}</ListItemIcon>
                 <ListItemText>{item.text}</ListItemText>
               </ListItem>
            ))}
       }
    <List>
  )
}

然而 :

// This code shows the warning "Each child in a list should have a unique "key" prop." when rendered

render(){
  const items = [
                  {text: 'files', icon: <FolderIcon />, path: '/my-files/'},
                  {text: 'shared files', icon: <SharedIcon />, path: '/shared-files'},
                 ]
  return(
    <List>
     { items.map(item => (
               <ListItem button>
                 <ListItemIcon>{item.icon}</ListItemIcon>
                 <ListItemText>{item.text}</ListItemText>
               </ListItem>
            ))}
      }
    <List>
  )
}

我真的不明白这两个版本有什么区别,除了我在第二个例子中使用了一个变量。

任何人都知道为什么?

标签: javascriptreactjsmaterial-ui

解决方案


推荐阅读