简体   繁体   中英

React useState hook not updating array for removed item

I have a react table that has a column with buttons, one to remove the row via removeRow(idx) callback. The handler correctly removes/filters out the corresponding row, however on subsequent attempts to remove more rows, the previously deleted row returns. Via the console logs, it appears React is not updating rowData even though the table shows a row being removed (albeit one at most). Every console.log('rowData', rowData) shows the original array.

I tried initializing the state to an empty array, but after some reworking, the removeRow(idx) function when clicked renders an empty table.

Anyone know what is going on here??

** UsersTable.js **

import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';

import { MDBDatatable, MDBBtn, MDBIcon } from 'mdbReactUiKit';
import Wrapper from '../Wrapper';
import styled from 'styled-components';

import { rows, cols } from '../../variables/Users';

...

export default function UsersTable() {
  const [colData, setColData] = useState(cols)
  const [rowData, setRowData] = useState(addCustomButtons(rows))
  
  function addCustomButtons(rows) {
    return rows.map((row, idx) => {
      return {
        ...row,
        index: idx,
        email: (
          <StyledLink
            to='#'
            onClick={(e) => {
              window.location.href = `mailto:${row.emailraw}`;
              e.preventDefault();
            }}
          >
            {row.emailraw}
          </StyledLink>
        ),
        buttons: (
          <>
            <StyledButton
              size='sm'
              floating
              className='message-btn'
              onClick={() => console.log(`send a message to ${row.emailraw}`)}
            >
              <MDBIcon icon='envelope' />
            </StyledButton>
            <StyledButton outline size='sm' floating className='call-btn' onClick={() => console.log(`edit user settings`)}>
              <MDBIcon icon='ellipsis-h' />
            </StyledButton>
            <StyledTrash
              size='sm'
              floating
              className='remove-user-btn'
              onClick={() => removeRow(idx)}
            >
              <MDBIcon icon="trash" />
            </StyledTrash>
          </>
        ),
      };
    })
  }

// does not work
  const deleteRow = (index) => {
    if (rowData.length > 0) {
      var updatedRows = [...rowData]
      console.log('1st rowData', updatedRows)

      var indexToRemove = updatedRows.findIndex(x => x.index === index)
      console.log('remove', indexToRemove, index)

      if (indexToRemove > -1) {
        updatedRows.splice(indexToRemove, 1)
        var newRows = addCustomButtons(updatedRows)

        console.log(newRows)

        setRowData(newRows)
        // setTableData((prevState) => {
        //   return {
        //     ...prevState,
        //     rows: newRows
        //   }
        // })
      }
    }
  }

// almost works
  const removeRow = (index) => {
    console.log('rowData', rowData)
    const oldRows = [...rowData]
    const updatedRows = oldRows.filter((row) => row.index !== index);
    console.log('updated', updatedRows)

    setRowData(updatedRows)

    setTimeout(() => {
      console.log('timer', rowData)
    }, 3000)
  }


  const Table = ({ colData, rowData }) => {
    let tableData = {
      columns: colData,
      rows: rowData
    }

    useEffect(() => {
      tableData = {
        columns: colData,
        rows: rowData
      }
    }, [rowData])

  
    return (
      <StyledTable
        hover
        striped
  
        data={tableData}
        entriesOptions={[5, 10, 20]}
        entries={10}
  
        fixedHeader
        maxHeight='460px'
      />
    )
  }

  return (
    <Wrapper>
      <TableContainer>
        <Table colData={colData} rowData={rowData} />
      </TableContainer>
    </Wrapper>
  );
}

Hello I think you should try to replace :

setRowData(updatedRows)

with:

setRowData([...updatedRows])

and log rowData to check if it worked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM