如何使列表中的每个 child 在 React 中都应该有一个唯一的 "key" 道具

How to make each child in a list should have a unique "key" prop in React

收集数据 →

    const gatherComps = (data) => {
        let competencyList = []
        let i = 1
        while (i < 6) {
          if (data && data.hasOwnProperty(`competency${i}`)) {
            competencyList.push(data[`competency${i}`])
          }
          i++
        }
        return competencyList
      }

准备数据 →

    const displayInfo = (singleCC, i) => {
        const result = singleCC.length
          ? singleCC.map((cc, ind) => {
              return ind < 1 ? (
                <div className="competencyHeadline">
                  <b>{cc}</b>
                </div>
              ) : (
                <div className="competencyDesc" key={ind}>
                  <i>{cc}</i>
                </div>
              )
            })
          : ""
        return (
          <div key={i}>
            <>{result}</>
          </div>
        )
      }

Return 数据 →

    <div className="Competencies">
        <div className="wrapper">
            {gatherComps(data).map((cc, i) => displayInfo(cc, i))}
        </div>
    </div>

我试过: key={i} key={`custom-name-title-` + i.toString()} key={ind} key={`custom-name-desc-` + ind.toString()} 和其他一些类似的东西,无法让这个警告消失。

我什至为 id={} 添加了相同的值,以确保它继续呈现唯一的 id,确实如此,但我仍然收到警告...

您缺少 <div className="competencyHeadline"> 的键值。你在 .map.

的第一次迭代中有那个

只需按照与您相同的方式添加自定义密钥即可:

const displayInfo = (singleCC, i) => {
  const result = singleCC.length
    ? singleCC.map((cc, ind) => {
        return ind < 1 ? (
          <div className="competencyHeadline" key={ind}> <------------ HERE
            <b>{cc}</b>
          </div>
        ) : (
          <div className="competencyDesc" key={ind}>
            <i>{cc}</i>
          </div>
        );
      })
    : '';
  return (
    <div key={i}>
      <>{result}</>
    </div>
  );
};