【问题标题】:How to resolve eslint missing key prop for element in array when not iterating?不迭代时如何解决数组中元素的eslint缺少关键道具?
【发布时间】:2022-01-16 18:30:32
【问题描述】:

对于以下代码,eslintreact/jsx-key: Missing 'key' prop for element in array 引发错误。

我知道我需要向我的数组添加键,但我不知道在哪里以及如何!

我该如何解决?

export default function App() {
  const [step, setStep] = useState(0);

  function handleClick() {
    setStep((step) => [1, 2, 0][step]);
  }

  const ComponentList = [
    <div>Step 1</div>,
    <div>Step 2</div>,
    <div>Step 3</div>
  ];

  return (
    <div>
      <button onClick={handleClick}>Increment Step</button>
      {ComponentList[step]}
    </div>
  );
}

【问题讨论】:

    标签: reactjs key eslint


    【解决方案1】:

    不建议使用索引作为键,您应该使用唯一标识符,但以此为例。

    export default function App() {
          const [step, setStep] = useState(0);
    
          function handleClick() {
            setStep((step) => [1, 2, 0][step]);
          }
    
          const ListItem = (step) => (<div>`Step ${step}`</div>)
    
          return (
            <div>
              <button onClick={handleClick}>Increment Step</button>
              <ListItem item={step}>
            </div>
          );
        }

    在此示例中,ListItem 甚至不需要键,因为我们没有遍历数组。但如果它是一个数组,那就是:

    list.map(step => <ListItem step={step} key={`list-item-${step.toString()}`}>)
    

    【讨论】:

      猜你喜欢
      • 2023-01-06
      • 2019-06-21
      • 2018-06-24
      • 2013-07-22
      • 1970-01-01
      • 2018-08-01
      • 1970-01-01
      • 2022-07-23
      • 2014-08-13
      相关资源
      最近更新 更多