网站搜索

javascript - .map 函数在内部方法中的索引


我的代码给我以下错误:

Warning: Encountered two children with the same key, `classroom-1278238`. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version.

我有这两部分代码使用了 .map 方法。我尝试将代码放在 <span key={index}></span> 之间,并在 map 内部定义 'index',但是 React JS Typescript 不接受这样做。

classroomFeatures.map((classroom_features: Types.ISelectOption) => {
                                        return (
                                          <React.Fragment key={'classroom_features-' + classroom_features.value}>
                                            <button className="multiple-info-tag small-tag text-capitalize">
                                              {classroom_features.label}
                                            </button>
                                            <br />
                                          </React.Fragment>
                                        );
                                      })
item.classroomInfo.feature_codes.map((featureCode: string) => {
                          const feature = ClassroomFeatureOptions.find(
                            (item: Types.ISelectOption) => item.value && item.value === featureCode
                          );
                          if (feature) {
                            classroomFeatures.push(feature);
                          }
                        });

答案#1

警告:遇到两个具有相同键的子元素,classroom-1278238。键应该是唯一的,以便组件在更新时保持其身份。非唯一键可能导致子元素被重复和/或遗漏 —— 这种行为不受支持,并可能在未来版本中发生变化。

此处的key应是唯一的。为 key 生成一个唯一的值:

key={'_'  +  Math.random().toString(36).substr(2, 9)}