У меня проблемы с таблицей Material UI. Я искал документ таблицы Material UI, который находится по адресу https://material-ui.com/components/tables/. Я хочу знать, как применить разбиение на страницы с моим Jscode «CheckListComponent.js», например «Пользовательские действия по разбивке на страницы» в этих документах. Я только что изменил createData, который находится в этом документе, на мои Jsondata. Теперь я путаю эту ошибку
CustomPaginationActionsTable
C:/workspace/spring-backend-3/frontend/src/component/PagenationTableComponent.js:117
114 | return (
115 | <TableContainer component = {Paper}>
116 | <Table className = {classes.table} aria-label = "custom pagination table">
> 117 | <TableBody>
| ^ 118 | {(rowsPerPage > 0
119 | ? rows.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
120 | : rows
View compiled
Я понимаю, что это значит, но я не понимаю, где я должен исправить. Подскажите пожалуйста как исправить. В Японии никто не подскажет, как исправить сейчас.
Контрольный список.js
import axios from 'axios'
const CHECKLIST_REST_API_URL = 'http://localhost:8080/api/users';
class CheckListService {
getList() {
return axios.get(CHECKLIST_REST_API_URL);
}
}
export default new CheckListService();
PagenationTableComponent.js
import React from 'react';
import PropTypes from 'prop-types';
import { makeStyles, useTheme } from '@material-ui/core/styles';
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 TableFooter from '@material-ui/core/TableFooter';
import TablePagination from '@material-ui/core/TablePagination';
import TableRow from '@material-ui/core/TableRow';
import Paper from '@material-ui/core/Paper';
import IconButton from '@material-ui/core/IconButton';
import FirstPageIcon from '@material-ui/icons/FirstPage';
import KeyboardArrowLeft from '@material-ui/icons/KeyboardArrowLeft';
import KeyboardArrowRight from '@material-ui/icons/KeyboardArrowRight';
import LastPageIcon from '@material-ui/icons/LastPage';
import CheckListService from '../services/CheckList';
const useStyles1 = makeStyles((theme) => ({
root: {
flexShrink: 0,
marginLeft: theme.spacing(2.5),
},
}));
function TablePaginationActions(props) {
const classes = useStyles1();
const theme = useTheme();
const { count, page, rowsPerPage, onChangePage } = props;
const handleFirstPageButtonClick = (event) => {
onChangePage(event, 0);
};
const handleBackButtonClick = (event) => {
onChangePage(event, page - 1);
};
const handleNextButtonClick = (event) => {
onChangePage(event, page + 1);
};
const handleLastPageButtonClick = (event) => {
onChangePage(event, Math.max(0, Math.ceil(count / rowsPerPage) - 1));
};
return (
<div className = {classes.root}>
<IconButton
onClick = {handleFirstPageButtonClick}
disabled = {page === 0}
aria-label = "first page"
>
{theme.direction === 'rtl' ? <LastPageIcon /> : <FirstPageIcon />}
</IconButton>
<IconButton onClick = {handleBackButtonClick} disabled = {page === 0} aria-label = "previous page">
{theme.direction === 'rtl' ? <KeyboardArrowRight /> : <KeyboardArrowLeft />}
</IconButton>
<IconButton
onClick = {handleNextButtonClick}
disabled = {page >= Math.ceil(count / rowsPerPage) - 1}
aria-label = "next page"
>
{theme.direction === 'rtl' ? <KeyboardArrowLeft /> : <KeyboardArrowRight />}
</IconButton>
<IconButton
onClick = {handleLastPageButtonClick}
disabled = {page >= Math.ceil(count / rowsPerPage) - 1}
aria-label = "last page"
>
{theme.direction === 'rtl' ? <FirstPageIcon /> : <LastPageIcon />}
</IconButton>
</div>
);
}
TablePaginationActions.propTypes = {
count: PropTypes.number.isRequired,
onChangePage: PropTypes.func.isRequired,
page: PropTypes.number.isRequired,
rowsPerPage: PropTypes.number.isRequired,
};
let rows = [];
rows = CheckListService.getList().then((response) => {
return response.data
});
const useStyles2 = makeStyles({
table: {
minWidth: 500,
},
});
export default function CustomPaginationActionsTable() {
const classes = useStyles2();
const [page, setPage] = React.useState(0);
const [rowsPerPage, setRowsPerPage] = React.useState(5);
const emptyRows = rowsPerPage - Math.min(rowsPerPage, rows.length - page * rowsPerPage);
const handleChangeEventPage = (event, newPage) => {
setPage(newPage);
};
const handleChangeEventRowsPerPage = (event) => {
setRowsPerPage(parseInt(event.target.value, 10));
setPage(0);
};
return (
<TableContainer component = {Paper}>
<Table className = {classes.table} aria-label = "custom pagination table">
<TableBody>
{(rowsPerPage > 0
? rows.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
: rows
).map((row) => (
<TableRow key = {row.listNo}>
<TableCell component = "th" scope = "row">
{row.listNo}
</TableCell>
<TableCell style = {{ width: 160 }} align = "right">
{row.saiyouDate}
</TableCell>
<TableCell style = {{ width: 160 }} align = "right">
{row.softwareName}
</TableCell>
</TableRow>
))}
{emptyRows > 0 && (
<TableRow style = {{ height: 53 * emptyRows }}>
<TableCell colSpan = {6} />
</TableRow>
)}
</TableBody>
<TableFooter>
<TableRow>
<TablePagination
rowsPerPageOptions = {[5, 10, 25, { label: 'All', value: -1 }]}
colSpan = {3}
count = {rows.length}
rowsPerPage = {rowsPerPage}
page = {page}
SelectProps = {{
inputProps: { 'aria-label': 'rows per page' },
native: true,
}}
onChangePage = {handleChangeEventPage}
onChangeRowsPerPage = {handleChangeEventRowsPerPage}
ActionsComponent = {TablePaginationActions}
/>
</TableRow>
</TableFooter>
</Table>
</TableContainer>
);
}
PostScript: я написал код, как указано ниже. затем я получил новую ошибку «useEffect» не определен в консоли. Поэтому я импортирую «import {useState} из« реакции »;» но не исправить. Что я должен сделать, чтобы скомпилировать?
export default function CustomPaginationActionsTable() {
const classes = useStyles2();
const [page, setPage] = React.useState(0);
const [rows, setRows] = React.useState([]);
const [rowsPerPage, setRowsPerPage] = React.useState(5);
const emptyRows = rowsPerPage - Math.min(rowsPerPage, rows.length - page * rowsPerPage);
const handleChangeEventPage = (event, newPage) => {
setPage(newPage);
};
const handleChangeEventRowsPerPage = (event) => {
setRowsPerPage(parseInt(event.target.value, 10));
setPage(0);
};
useEffect(() => {
CheckListService.getList().then((response) => setRows(response.data)); // you may need to check if response.data returns an array, otherwise you will face errors.
}, [])
return (
<TableContainer component = {Paper}>
<Table className = {classes.table} aria-label = "custom pagination table">
<TableBody>
{(rowsPerPage > 0
? rows.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
: rows
).map((row) => (
<TableRow key = {row.listNo}>
<TableCell component = "th" scope = "row">
{row.listNo}
</TableCell>
<TableCell style = {{ width: 160 }} align = "right">
{row.saiyouDate}
</TableCell>
<TableCell style = {{ width: 160 }} align = "right">
{row.softwareName}
</TableCell>
</TableRow>
))}
{emptyRows > 0 && (
<TableRow style = {{ height: 53 * emptyRows }}>
<TableCell colSpan = {6} />
</TableRow>
)}
</TableBody>
<TableFooter>
<TableRow>
<TablePagination
rowsPerPageOptions = {[5, 10, 25, { label: 'All', value: -1 }]}
colSpan = {3}
count = {rows.length}
rowsPerPage = {rowsPerPage}
page = {page}
SelectProps = {{
inputProps: { 'aria-label': 'rows per page' },
native: true,
}}
onChangePage = {handleChangeEventPage}
onChangeRowsPerPage = {handleChangeEventRowsPerPage}
ActionsComponent = {TablePaginationActions}
/>
</TableRow>
</TableFooter>
</Table>
</TableContainer>
);
}
добро пожаловать сы-тории. вам нужно удалить переменную row
снаружи из вашей функции. вместо этого включите в свой CustomPaginationActionsTable
состояние строки. затем используйте useEffect
, чтобы получить строки при монтировании компонента.
import React, { useEffect } from 'react'; // import useEffect
export default function CustomPaginationActionsTable() {
const classes = useStyles2();
const [page, setPage] = React.useState(0);
const [rows, setRows] = React.useState([]);
const [rowsPerPage, setRowsPerPage] = React.useState(5);
useEffect(() => {
CheckListService.getList().then((response) => setRows(response.data)); // you may need to check if response.data returns an array, otherwise you will face errors.
}, []) // passing an empty array will call this function only at component mount
вам нужно импортировать useEffect import { useEffect } from 'react'
Спасибо что учите меня. Я редактирую и добавляю новую проблему в постскриптум внизу моего вопроса. Пожалуйста, скажите мне.