问题
Unable to add multiple rows properly. Follow below steps:
- Click on sample excel sheet to download it.
- Once same sheet is imported all data is shown.
- Column values can be updated by clicking on its value and changing it.
However When I add more rows, it appears twice and unable to change its column value by clicking on it.
Even after adding rows to it. There is no key attached to that row as shown below:
Before adding rows:
After adding rows:
Codesandbox link:
https://codesandbox.io/s/github/abiodunsulaiman694/excel-app/tree/master/
回答1:
Instead of index and if your object array don't have unique value (like id) you can use the nanoid package and then in your map function do something like this in Excelenderer function :
ExcelRenderer(fileObj, (err, resp) => {
if (err) {
console.log(err);
} else {
let newRows = [];
resp.rows.slice(1).map((row) => {
if (row && row !== "undefined") {
newRows.push({
key: nanoid(),
name: row[0],
age: row[1],
gender: row[2]
});
}
});
and in handleAdd function:
handleAdd = () => {
const { count, rows } = this.state;
const newData = {
key: nanoid(),
name: "User's name",
age: "22",
gender: "Female"
};
this.setState({
rows: [newData, ...rows],
count: count + 1
});
};
it will generate an unique key by calling nanoid()
from nanoid library.
carefull
don't use nanoid in render function
like explain in nanoid doc :
Do not call nanoid in the key prop. In React, key should be consistent among renders.
This is the bad example:
/* DON’T DO IT */
here sandbox
来源:https://stackoverflow.com/questions/65494848/unable-to-add-rows-properly