【发布时间】: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