Reactjs 遇到两个 children 具有相同的键,`NaN`。键应该是唯一的

Reactjs Encountered two children with the same key, `NaN`. Keys should be unique

我尝试了不同的方法来消除 遇到两个使用相同密钥 NaN 的 children。键应该是唯一的,这是部分日志:

in DynamicFields (at TableHeader.js)
in th (at TableHeader.js)
in TableHeader

这基本上就是 TableHeader.js 组件的这一点,完整代码粘贴在本页下方:

return (
        <th key={cleanTitle + - + index}
            ref={(th) => th = th}
            style={{width:width}}
            data-col={cleanTitle}
         >

         <span className="header-cell" key={index*11}>{title} </span>
         <DynamicFields key={header.index+title} parentIndex={(index + 3) + title} />
       </th>
      );

我已经通读了这篇关于 keys 和 reactjs 的 ,跟着它,但错误仍然没有停止。

这是渲染数据表所涉及的 3 个组件:

MyDatatable.js
import React from "react";
import TableHeader from "./TableHeader";

const MyDatatable = (props) => {
  columnHeaders =  [
        {title: "Id" , accessor: 'id' , index: 0},
        {title: "Name" , accessor: 'name', width: "300px", index: 2}
        ]
        
   rowData = [
      {id: 1, name: 'a', age: 29, qualification: 'B.com', rating: 3, profile: 'ps'},
      {id: 2, name: 'b', age: 35, qualification: 'B.Sc', rating: 5, profile: 'h'}
   ]
        
  const [headers, setHeaders] = React.useState(columnHeaders);

  const [data, setData] = React.useState(rowData)
  
  const  renderContent = () => {
    let contentView = data.map((row, rowIdx) => {
    let id = row[keyField];
    let tds = headers.map((header, index) => {
    let content = row[header.accessor];

    return (
      <td key={index} data-id={id} data-row={rowIdx}>
        {content}
      </td>
     );
   });
        
   return (
     <tr key={rowIdx}>
       {tds}
     </tr>
    );
            //
  }); //closes contentView variable

 return contentView;
}

const renderTable = () => {
  let title = props.title || "DataTable";
  let contentView = renderContent();
          
  return (
    <table className="data-inner-table table-responsive">
      <caption className="data-table-caption">
        {title}
      </caption>
      <thead>
        <tr>
          <TableHeader headers={headers} />
        </tr>
      </thead>

      <tbody>
        {contentView}
      </tbody>
    </table>
  )}  

  return (
    <React.Fragment>
      <div className={props.className}>
        {renderTable() }
      </div>
    </React.Fragment>
  )
}
TableHeader.js
import React from "react";
import DynamicFields from "../DynamicFields";

const TableHeader = (props) => {
  let FieldTypes = ["text", "dropdown"];
  
  const renderTableHeader = () => {

    headers.sort((a, b) => {
      if (a.index > b.index) return 1;
      return -1
    });

    const headerView = headers.map((header, index) => {
      let title = header.title;
      let cleanTitle = header.accessor;
      let width = header.width;

      return (
        <th key={cleanTitle + - + index}
            ref={(th) => th = th}
            style={{width:width}}
            data-col={cleanTitle}
         >

         <span className="header-cell" key={index*11}>{title} </span>
         <DynamicFields key={header.index+title} parentIndex={(index + 3) + title} />
       </th>
      );

  } );

    return headerView;
  }

  return(
    <React.Fragment>
     {renderTableHeader()}
    </React.Fragment>
  )
}
DynamicFields.js
import React, { useState, useEffect, useRef } from "react"

const DynamicFields = (props) => {
  const  optionsHash =  ['Checkbox', 'Dropdown', 'boolean', 'Single line text'];

  const [showDynamicField, setShowDynamicField ] = useState(false);

  // const dropdownRef = useRef();
  
  
   const handleShowDynamicField = (event) => {
     setShowDynamicField(!showDynamicField);
   };

  return (
    <React.Fragment>
      <i className="bi bi-chevron-compact-down" onClick={handleShowDynamicField}></i>

     {showDynamicField &&
       optionsHash.map( (val, idx) => {
                return(
                 <li key={val-idx}  value={val} className="dropdown-item"> {val} </li>
                )
       })
     }
    </React.Fragment>
  )
}

-是减法运算符,会导致key={val-idx}(string - number => NaN)的问题。
大概你想使用 - 作为分隔符,所以你将它用作字符串: key={val + '-' + idx} 或 key={`${val}-${idx}`}

在这种情况下,由于 optionsHash 具有所有唯一字符串,您可以仅使用 key={val}.

key={cleanTitle + - + index} 起作用的原因是因为它的计算结果为 cleanTitle + (- +index),将负数添加到允许的字符串(但令人困惑)。