首页 > 解决方案 > 使用反应状态附加到对象

问题描述

我已经在这个问题上停留了几个小时,我不知道如何解决它。
我使用材料 UI 表来显示数据。当前设置填充下拉选项,用户可以从中选择组合。

该选择被设置为状态,并显示在表格上。当我进行第二次选择时,问题就出现了,它不是附加数据,而是覆盖旧数据。

最终结果应该是选项列表。不仅仅是最新的提交。

最后,我只传递了一个 arg 用于测试目的;在生产中将有四个参数。

任何帮助表示赞赏。

**main Page**
 const [dropdownState, setDropdownState] = useState({
        GridLOE: "",
        GridSelect: "",
    });


const handleDropdown = (event) => {
        setDropdownState({
            ...dropdownState,
            [event.target.name]: event.target.value,
        });
    };

    const gridLineOfEffortData = [
        "Crisis",
        "Activities",
        "Conflicts",
        "Networks",
        "Prioritization",
    ]

    const gridLineOfEffortOptionsData = [
        "Minimal",
        "Enhancing",
        "Critical",
    ]

    // DATA GRID
    const [dataGrid, setDataGrid] = useState({
        data: []
    })

    function createData(loeName, minimal, enhancing, critical) {
        return { loeName, minimal, enhancing, critical }
    }

    const handleGrid = () => {
        setDataGrid({
            ...dataGrid,
            data: [
                createData(dropdownState.GridLOE)
            ]
        })
        console.log(dropdownState.GridLOE)
    };

主页选择下拉菜单并提交

<Grid container spacing={5} padding={3}>
   <Grid item lg={12} sm={12} xs={12}>
      <TableGridPrioritization
        rows={dataGrid.data}></TableGridPrioritization>
   </Grid>
   <Grid item lg={4} sm={6} xs={12}>
         <FieldDropdown
            selectId={"GridLOE"}
            selectTitle={"Select LOE"}
            selectValue={dropdownState.GridLOE}
            selectList={gridLineOfEffortData}
            handleChange={handleDropdown}
          >
         </FieldDropdown>
   </Grid>
   <Grid item lg={4} sm={6} xs={12}>
          <FieldDropdown
            selectId={"GridSelect"}
            selectTitle={"Minimal, enhancing, or critical"}
            selectValue={dropdownState.GridSelect}
            selectList={gridLineOfEffortOptionsData}
            handleChange={handleDropdown}
          >
          </FieldDropdown>
   </Grid>
   <Grid item lg={4} sm={6} xs={12}>
     <Button variant="contained" color="secondary" size="large" onClick={handleGrid}>ADD TO GRID</Button>
  </Grid>

进口组件

// BASIC 
import React from "react";
import { withStyles } from "@material-ui/core/styles";
import styles from "../../components/RoutingTool/Theme";
// NEEDS REMOVING
import { makeStyles } from '@material-ui/core/styles';
// ELEMENTS 
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableContainer from '@material-ui/core/TableContainer';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Paper from '@material-ui/core/Paper';

const StyledTableCell = withStyles((theme) => ({
  head: {
    backgroundColor: theme.palette.common.black,
    color: theme.palette.common.white,
  },
  body: {
    fontSize: 14,
  },
}))(TableCell);

const StyledTableRow = withStyles((theme) => ({
  root: {
    '&:nth-of-type(odd)': {
      backgroundColor: theme.palette.action.hover,
    },
  },
}))(TableRow);

const useStyles = makeStyles({
  table: {
    minWidth: 700,
  },
});

export const TableGridPrioritization = props => {
  const classes = useStyles();

  return (
    <TableContainer component={Paper} className={props.classes.tablePrioritizationDataGrid}>
      <Table className={classes.table} aria-label="customized table">
        <TableHead>
          <TableRow>
            <StyledTableCell>Line of Effort</StyledTableCell>
            <StyledTableCell align="right">Minimal</StyledTableCell>
            <StyledTableCell align="right">Enhancing</StyledTableCell>
            <StyledTableCell align="right">Critical</StyledTableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {props.rows.map((row) => (
            <StyledTableRow key={row.loeName}>  
              <StyledTableCell component="th" scope="row">
                {row.loeName}
              </StyledTableCell>
              <StyledTableCell align="right">{row.minimal}</StyledTableCell>
              <StyledTableCell align="right">{row.enhancing}</StyledTableCell>
              <StyledTableCell align="right">{row.critical}</StyledTableCell>
            </StyledTableRow>
          ))}
        </TableBody>
      </Table>
    </TableContainer>
  );
}

标签: reactjsreact-hooks

解决方案


由于您dataGrid是其中的对象,data因此您需要获取所有 currentdata而不是 currentdataGrid但正在执行data:[...data, NEWDATA]. 下面的代码应该可以工作。

// DATA GRID
const [dataGrid, setDataGrid] = useState({
    data: []
})

const handleGrid = () => {
    setDataGrid({
        data: [...dataGrid.data,
            createData(dropdownState.GridLOE)
        ]
    })
    console.log(dropdownState.GridLOE)
};

推荐阅读