繁体   English   中英

React useState钩子不更新已删除项目的数组

[英]React useState hook not updating array for removed item

我有一个反应表,其中有一列带有按钮,一个通过removeRow(idx)回调删除该行。 处理程序正确删除/过滤掉相应的行,但是在随后尝试删除更多行时,先前删除的行返回。 通过控制台日志,React 似乎没有更新 rowData,即使表格显示有一行被删除(尽管最多一个)。 每个console.log('rowData', rowData)都显示原始数组。

我尝试将状态初始化为一个空数组,但经过一些修改后,单击removeRow(idx)函数会呈现一个空表。

有谁知道这里发生了什么??

** 用户表.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>
  );
}

您好,我认为您应该尝试更换:

设置行数据(更新行)

和:

setRowData([...updatedRows])

并记录 rowData 以检查它是否有效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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