Проблемы с React.useState () - PullRequest
0 голосов
/ 27 апреля 2020

Я не понимаю, почему новая строка не появляется после нажатия кнопки. Вывод через console.log показывает, что строка была добавлена ​​в таблицы var правильно. Другой вопрос, почему я вижу, что новая строка была добавлена ​​в таблицу даже в выводе console.log (таблицы), прокомментированном // 1? Этот вывод происходит до того, как я добавляю строку.

Код был испорчен после вставки здесь, надеюсь, он все еще читается.

function Development() {
  const classes = useStyles();

  const [tables, setTables] = React.useState([
    {
      tableName: 'Table1',
      rows: [
        {
          colId: 1,
          primaryKey: 11,
          colName: 'Name1',
          datatype: 'Type1',
          length: 111,
          nulls: 'n1'
        }, 
        {
          colId: 2,
          primaryKey: 22,
          colName: 'Name2',
          datatype: 'Type2',
          length: 222,
          nulls: 'n2'          
        }
      ]
    }, 
    {
      tableName: 'Table2',
      rows: [
        {
          colId: 3,
          primaryKey: 33,
          colName: 'Name3',
          datatype: 'Type3',
          length: 333,
          nulls: 'n3'
        }, 
        {
          colId: 4,
          primaryKey: 44,
          colName: 'Name4',
          datatype: 'Type4',
          length: 444,
          nulls: 'n4'          
        }
      ]
    }
  ]);

  const addRow = () => {
    console.log(tables); // 1
    var tempList = tables;

    tempList.some((table) => {
      if (table.tableName === "Table1") {
       table.rows.push({colId: 5, primaryKey: 55, colName: 'Name5', datatype: 'Type5', length: 555, 
       nulls: 'n5'});
      }
    });
    setTables(tempList);
 }


  return (
    <div>
    <Card className={[classes.mainCard, classes.card].join(' ')}>
      {tables.map((tb) => {
        var rows = tb.rows.map(function(row) {
          return (
              <TableRow key={row.colId}>
                <TableCell component="th" scope="row">
                  {row.colId}
                </TableCell>
                <TableCell>{row.primaryKey}</TableCell>
                <TableCell>{row.colName}</TableCell>
                <TableCell>{row.datatype}</TableCell>
                <TableCell>{row.length}</TableCell>
                <TableCell>{row.nulls}</TableCell>
              </TableRow>
          )
        });

    return (
      <TableContainer component={Paper}>{tb.tableName}
        <Table className={classes.table} aria-label="simple table">
          <TableHead>
            <TableRow>
              <TableCell>COL ID</TableCell>
              <TableCell>PRIMARY KEY</TableCell>
              <TableCell>COLNAME</TableCell>
              <TableCell>DATATYPE</TableCell>
              <TableCell>LENGTH</TableCell>
              <TableCell>NULLS</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {rows}
          </TableBody>
        </Table>

      </TableContainer> 
    )
  })} 
</Card>
<Button className={classes.btn2} color="primary" variant="outlined" onClick={addRow}>Add Row</Button>
</div>
  );
}

1 Ответ

1 голос
/ 27 апреля 2020

Проблема в том, что вы не обновляете массив tempList после того, как вы в него добавили sh. Использование some не лучший подход, я думаю, что использование map было бы лучше, потому что он возвращает новый массив, и вы можете обновить содержимое в обратном вызове.

const addRow = () => {
  console.log(tables); // 1
  // You should return the updated array after pushing
  const updatedTable = tables.map((table) => {
    if (table.tableName === "Table1") {
      // Push into this table's child
      table.rows.push({
        colId: 5,
        primaryKey: 55,
        colName: 'Name5',
        datatype: 'Type5',
        length: 555,
        nulls: 'n5'
      });
    }

    // Return the element of the array
    return table;
  });

  setTables(updatedTable);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...