【问题标题】:How do I add rows to a table in React Hooks without getting duplicates?如何在 React Hooks 中向表中添加行而不重复?
【发布时间】:2021-12-29 16:49:50
【问题描述】:

我正在尝试使用反应钩子创建数据表,但我的状态中不断出现重复行。这是我获取值进行一些操作然后调用我的函数来更新状态的调用:

var tableRowIndex = 0;
const CoinTable = () => {
    const baseURL = 'endpoint/';
    const [tableRows, setRows] = useState([] as any);


    const getCurrentPrice = async (inputs: any) => {
        const response = await axios.get(`${baseURL}${inputs.currency}/USD`)
        let currentPrice = response.data
        inputs.cryptoPrice = currentPrice.rate;
        let coinsRequired = inputs.amount / inputs.cryptoPrice;
        inputs.amtCrypto = coinsRequired.toFixed(8);
        addNewRow(inputs)
    }

这是我尝试更新状态的函数

 const addNewRow = (inputs: any) => {
        tableRowIndex++
        inputs.index = tableRowIndex
        setRows([...tableRows, inputs])
    }

这是我通过行映射并在 JSX 中输出的其余组件。

const rows = tableRows.map((row: any) => {
        return (
            <TableRow
                key={tableRowIndex}
                addNewRow={addNewRow}
                removeRow={removeRowHandler}
                getCurrentPrice={getCurrentPrice}
                row={row}
            />
        )
    })
    
    return (
        <>
            <AddItem
                getCurrentPrice={getCurrentPrice}
            />
            {tableRows.length > 0 &&
                <table>
                    <tbody>
                        <tr>
                            <th>Merchant</th>
                            <th>Item</th>
                            <th>Amount(Crypto)</th>
                            <th>Currency</th>
                            <th>Price/crypto(USD)</th>
                            <th>Amount(USD)</th>
                        </tr>
                        {rows}
                    </tbody>
                </table>

            }
        </>
    )
}

export default CoinTable;

Inputs 是包含要呈现为新行的用户输入的对象。我如何使用扩展运算符更新状态似乎是一个问题,但我不确定。

【问题讨论】:

  • 映射到行的数据是否具有 GUID 或任何可以测试/断言唯一性的唯一字段属性?此外,使用映射数组索引不是理想的 React 键使用,您应该避免使用索引,而是使用 GUID 或唯一字段属性。除此之外,您在删除重复项方面已经尝试过什么?
  • 所以映射的数据默认没有 GUID 或任何 ID,因此我尝试手动添加。您是否认为这种重复必须与缺少密钥有关。鉴于我在控制台中收到有关密钥用法重复的警告。

标签: arrays reactjs react-hooks jsx


【解决方案1】:

看起来好像您使用单个 tableRowIndex "global" 值作为每个映射元素的 React 键。您可能打算使用row indexgenerated inaddNewRowwhen adding an element to thetableRows` 状态。

const addNewRow = (inputs: any) => {
  tableRowIndex++;
  inputs.index = tableRowIndex; // <-- assigned here
  setRows([...tableRows, inputs]);
}

...

const rows = tableRows.map((row: any) => {
  return (
    <TableRow
      key={row.index} // <-- used here
      addNewRow={addNewRow}
      removeRow={removeRowHandler}
      getCurrentPrice={getCurrentPrice}
      row={row}
    />
  )
})

更惯用的方法是调用此增强属性id,因此它大量很清楚,它不是任何数组索引,实际上是分配给每个元素的唯一值。我什至会说您可能想要使用为您生成 GUID 的库。 uuid 很棒。

import { v4 as uuidV4 } from 'uuid';

...

const addNewRow = (inputs: any) => {
  setRows(rowData => [
    ...rowData,
    {
      ...inputs,   // <-- don't mutate inputs object
      id: v4uuid() // <-- assign unique id
    },
  ]);
}

...

const rows = tableRows.map((row: any) => {
  return (
    <TableRow
      key={row.id}
      addNewRow={addNewRow}
      removeRow={removeRowHandler}
      getCurrentPrice={getCurrentPrice}
      row={row}
    />
  )
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-19
    • 2021-07-12
    • 1970-01-01
    • 2012-08-07
    • 1970-01-01
    • 2020-06-07
    • 1970-01-01
    • 2021-12-31
    相关资源
    最近更新 更多