首页 > 解决方案 > reactjs 如何在表格中显示过滤后的数据?

问题描述

如何在表格中显示过滤后的数据?我在这里发布问题之前所做的事情是我已经完成了过滤器,我可以从数据库中检索数据,并且我确定它正在工作,因为我可以使用控制台看到它,我的问题是我不知道如何将其显示在表格内。我被困在这里。谢谢。

注意数据将在用户使用过滤器后显示。

//header
.....
function createData(datetime, user, appCode, module, transaction, table, id, record) {
  return { datetime, user, appCode, module, transaction, table, id, record };
}
//this is were i need to display the data in `const rows`
const rows = [
  //this is where i want to post or display may data
  createData('July 22, 2021 | 07:34:12 AM', 'John Doe', 'App', 'Module', 'Transaction', 'Table','ID', 'Record'),
];

const AuditLogs = () => {
  const [filtered, setFiltered] = useState("");
  const classes = useStyles();
  const [reason, setReason] = useState("");
  const [app, setApp] = useState("");
  const [transaction, setTransaction] = useState("");
  const classes = useStyles();
  const [page, setPage] = React.useState(0);
  const [rowsPerPage, setRowsPerPage] = React.useState(10);
  const handleChangePage = (event, newPage) => {
    setPage(newPage);
  };
  const handleChangeRowsPerPage = (event) => {
    setRowsPerPage(+event.target.value);
    setPage(0);
  };
  const handleChangeTransaction = (event) => {
    setTransaction(event.target.value);
  };
  const handleChangeApp = (event) => {
    setApp(event.target.value);
  };

  const handleUpdateButton = async ()=>{
    const filter = await getaudit(app, transaction);
    //console.log(filter)
    setFiltered(filter)
    if (filter.status == 200){
      Swal.fire({
        icon: 'success',
        title: 'Successful.',
        text: 'Group has been successfully added.',
      })
    }else{
      Swal.fire({
        icon: 'error',
        title: 'Oops',
        text: 'Something went wrong.',
      })
    }
  }

  return (
    <Paper className={classes.root}>
      <div style={{height: 'auto', width: '100%', padding: 8, backgroundColor: '#fffS'}}>
        <Grid container>
          <Grid item xs={12} md={6} lg={6}>
            <h4 style={{margin: 8}}>Audit Logs</h4> 
          </Grid>
          <Grid item xs={9} md={4} lg={4}>
            <TextField
              id="standard-full-width"
              // style={{ minHeight: 22, marginBottom: 4 ,}}
              placeholder="Search"
              fullWidth
              margin="dense"
              InputLabelProps={{
                shrink: true,
              }}
            />
          </Grid>
          <Grid item xs={3} md={2} lg={2} style={{padding: 8}}>
            <div className={classes.root}>
              <IconButton aria-label="delete" color="primary" >
                <SearchRoundedIcon />
              </IconButton>
              <IconButton aria-label="delete" color="primary">
                <CloudDownloadSharpIcon />
              </IconButton>
            </div>
          </Grid>
        </Grid>
        <Grid container>
          <Grid container xs={12} sm={10} md={10} lg={10}
                direction="row"
                justifyContent="center"
                alignItems="center">
            <Grid item xs={12} sm={6} md={6} lg={6} style={{padding: 15, paddingBottom: 0, alignItems: 'center'}}>
              <DateRangePickerComponent id="daterangepicker" placeholder='Select a range' //startDate={} endDate={} 
              style={{paddingTop: 10, fontSize: 16}}
              />
            </Grid>
            <Grid item xs={12} sm={6} md={6} lg={6} style={{padding: 15, alignItems: 'center'}}>
            <FormControl className={classes.formControl}>
              <InputLabel htmlFor="age-native-simple">Application</InputLabel>
              <Select
                value={app}
                onChange={handleChangeApp}
              >
                <MenuItem  value="EAM">EAM</MenuItem>
                <MenuItem value="DMS">DMS</MenuItem>
                <MenuItem value="HRIS">HRIS</MenuItem>
              </Select>
            </FormControl>
            </Grid>
            <Grid item xs={12} sm={6} md={6} lg={6} style={{padding: 15, alignItems: 'center'}}>
            <FormControl className={classes.formControl}>
              <InputLabel htmlFor="age-native-simple">Transaction</InputLabel>
              <Select
                fullWidth
                value={transaction}
               onChange={handleChangeTransaction}
              >
                <MenuItem value="Insert">Insert</MenuItem>
                <MenuItem value="Delete">Delete</MenuItem>
                <MenuItem value="Update">Update</MenuItem>
              </Select>
            </FormControl>
            </Grid>
          </Grid>
          <Grid container xs={12} sm={2} md={2} lg={2}
                direction="row"
                justifyContent="center"
                alignItems="center">
            <Grid item xs={12} style={{padding: 8}}>
              <Button onClick={handleUpdateButton} variant="contained" color="primary" fullWidth>
                Apply Filters
              </Button>
            </Grid>
          </Grid>
        </Grid>
      </div>
      <TableContainer className={classes.container}>
        <Table>
          <TableHead>
            <TableRow>
              {columns.map((column) => (
                <TableCell
                  key={column.id}
                  align={column.align}
                  style={{ minWidth: column.minWidth }}
                >
                  {column.label}
                </TableCell>
              ))}
            </TableRow>
          </TableHead>
          <TableBody>
            {rows.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage).map((row) => {
              return (
                <TableRow hover role="checkbox" tabIndex={-1} key={row.code}>
                  {columns.map((column) => {
                    const value = row[column.id];
                    return (
                      <TableCell key={column.id} align={column.align}>
                        {column.format && typeof value === 'number' ? column.format(value) : value}
                      </TableCell>
                    );
                  })}
                </TableRow>
              );
            })}
          </TableBody>
        </Table>
      </TableContainer>
      <TablePagination
        rowsPerPageOptions={[10, 25, 100]}
        component="div"
        count={rows.length}
        rowsPerPage={rowsPerPage}
        page={page}
        onPageChange={handleChangePage}
        onRowsPerPageChange={handleChangeRowsPerPage}
      />
    </Paper>
  );
};

这是我从过滤后得到的结果

在此处输入图像描述

更新:我通过添加此代码收到此错误

        {filtered.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage).map((row) => {
                   console.log(filtered)
                   console.log("ss", filtered.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage))

在此处输入图像描述

标签: reactjsreact-hooks

解决方案


您正在映射rows,这似乎是假数据。看起来您的真实数据位于 中filtered,而您从未使用过。

首先,初始化filtered为与您的预期结构匹配的内容。 rows是一个数组,也可以创建filtered一个数组:

const [filtered, setFiltered] = useState([]);

当您调用 时setFiltered,请专门给它您想要的数据数组:

setFiltered(filter.data || []);

(以防响应是错误或以某种方式失败并且data不存在,这将默认为空数组。单独处理错误。)

然后在您的渲染中,使用filtered代替rows(您不再需要):

{filtered.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage).map((row) => {
  //...
})}

推荐阅读