【问题标题】:Key is defined but it warns "Each child in a list should have a unique key prop"键已定义,但它警告“列表中的每个孩子都应该有一个唯一的键道具”
【发布时间】:2020-05-09 11:15:35
【问题描述】:

虽然我为 SearchDropDownItem 定义了一个键,但它显示了一个警告

组件下拉

filteredItems.length > 0 ? (
  filteredItems.map(item => {
    return (
      <SearchDropDownItem
        item={item}
        buttonTitle={{ buttonJoin: content.buttonJoin }}
        onItemSelect={onItemSelect}
      />
    );
  })
) : (
  <SearchDropDownItem emptyList={content.noCommunityFound} />
)

searchDropDownItem 组件:

const SearchDropDownItem = ({
  item = {   },
  onItemSelect,
  buttonTitle = "",
  emptyList
}) => {
  return (
    <DropdownItem key={item.id || 1}>
      {!emptyList ? (
        <Box>
          <Span>{item.name} </Span>
          <JoinButton
            item={item}
            index={item.id}
            onSuccess={onItemSelect}
            content={buttonTitle}
          />
        </Box>
      ) : (
        <Box>
          <Span>{item.emptyList}</Span>
        </Box>
      )}
    </DropdownItem>
  );
};

警告列表中的每个孩子都应该有一个唯一的“key”道具。检查SearchBox的渲染方法。 在 SearchDropDownItem 中(在 SearchBox/index.jsx:52)

【问题讨论】:

  • key需要在DropDown中,也就是地图所在的地方。

标签: javascript arrays reactjs react-native ecmascript-6


【解决方案1】:

您应该将密钥放在您使用SearchDropdownItem 的位置,因此在循环中。

filteredItems.length > 0 ? (
  filteredItems.map(item => {
    return (
      <SearchDropDownItem
        key={item.id} // <-- This is where it has to be
        item={item}
        buttonTitle={{ buttonJoin: content.buttonJoin }}
        onItemSelect={onItemSelect}
      />
    );
  })
) : (
  <SearchDropDownItem emptyList={content.noCommunityFound} />
)

关于 React 中键的文档:https://reactjs.org/docs/lists-and-keys.html#keys

【讨论】:

    【解决方案2】:

    我收到了同样的警告信息: Warning: Each child in a list should have a unique "key" prop.

    但是,我的问题和解决方案与接受的答案有点不同。我认为将我的解决方案添加到这个问题可能会对某人有所帮助。

    我正在使用具有唯一键的第 3 方组件。但是,当我使用循环动态生成组件的多个实例时,我收到了上面的警告消息。

    在我向组件添加一个关键道具后,警告消失了。这个键不是组件 props 的一部分。

    let filterJSX = [];
    let i = 0; 
    for (let [key1, value1] of Object.entries(state.filterListNew)) { 
        i++; 
        filterJSX.push(
            <MultiSelectModalField
                key={i.toString()} // I added this one
    
                items={optionList}
                uniqueKey="value"
                displayKey="name"
                // more properties here... 
            />
        );
    } 
    

    【讨论】:

      猜你喜欢
      • 2023-02-17
      • 2019-08-04
      • 2021-01-12
      • 2022-06-28
      • 2021-03-20
      • 2019-12-05
      • 2021-09-05
      • 2020-03-01
      • 1970-01-01
      相关资源
      最近更新 更多