У меня был функциональный компонент таблицы, я попытался применить флажок к нему с помощью пользовательской сети, но я всегда получаю «максимальную глубину обновления превышенной». Я не знаю, что делать. < /P>
import React, { useEffect, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { usePagination, useRowSelect, useSortBy, useTable } from "react-table";
import Icon from "@mui/material/Icon";
import Table from "@mui/material/Table";
import TableBody from "@mui/material/TableBody";
import TableContainer from "@mui/material/TableContainer";
import TableRow from "@mui/material/TableRow";
import pxToRem from "assets/theme/functions/pxToRem";
import classNames from "classnames";
import MDBox from "components/MDBox";
import MDPagination from "components/MDPagination";
import MDDataTableBodyCell from "components/MDTable/MDDataTableBodyCell";
import MDDataTableHeadCell from "components/MDTable/MDDataTableHeadCell";
import MDTypography from "components/MDTypography";
import { useMaterialUIController } from "context";
import useAppData from "context/AppContext";
import PropTypes from "prop-types";
import "regenerator-runtime/runtime.js";
export default function Table7({
tableColumn,
searchResult,
searchAction,
sizePerPage,
paginationStyle,
isSorted,
noEndBorder,
pageKeyMap,
isPaginationServer,
initialPageSize,
buttonInRow,
hideHeader,
hideTotalEntries,
fullwidth,
rowClasses
}) {
const { t } = useTranslation();
const [controller] = useMaterialUIController();
const { gridSpace, rowGap, columnGap } = controller;
const { getSearchHistory } = useAppData();
const columnsData = useMemo(() => tableColumn, [tableColumn]);
const searchResultData = isPaginationServer
? searchResult
: {
currentPage: 1,
pageSize: sizePerPage,
total: searchResult.length,
list: searchResult
}
const initialState = useMemo(() => {
const searchHistory = getSearchHistory(pageKeyMap);
return {
pageSize: searchHistory.pageSize ?? initialPageSize,
pageIndex: searchHistory.page ? searchHistory.page - 1 : 0,
}
}, [initialPageSize]);
const IndeterminateCheckbox = React.forwardRef(
({ indeterminate, ...rest }, ref) => {
const defaultRef = React.useRef()
const resolvedRef = ref || defaultRef
React.useEffect(() => {
resolvedRef.current.indeterminate = indeterminate
}, [resolvedRef, indeterminate])
return (
)
}
)
const {
getTableProps,
getTableBodyProps,
headerGroups,
prepareRow,
rows,
page,
pageOptions,
canPreviousPage,
canNextPage,
gotoPage,
previousPage,
nextPage,
pageCount,
setPageSize,
state: { pageSize, pageIndex, sortBy, selectedRowIds }
} = useTable({
columns: columnsData,
data: searchResultData.list ?? [],
manualSortBy: isPaginationServer,
manualPagination: isPaginationServer,
pageCount: Math.ceil(searchResultData.total / searchResultData.pageSize),
initialState: initialState,
},
useSortBy,
usePagination,
useRowSelect,
hooks => {
hooks.visibleColumns.push(columns => [
// Let's make a column for selection
{
id: 'selection',
// The header can use the table's getToggleAllRowsSelectedProps method
// to render a checkbox
Header: ({ getToggleAllPageRowsSelectedProps }) => (
),
// The cell can use the individual row's getToggleRowSelectedProps method
// to the render a checkbox
Cell: ({ row }) => (
),
},
...columns,
])
}
)
const searchHistory = getSearchHistory(pageKeyMap);
useEffect(() => {
if (isPaginationServer) {
if (pageIndex !== searchHistory.page - 1) {
gotoPage(0);
}
}
}, [searchHistory]);
useEffect(() => {
if (isPaginationServer) {
searchHistory.page = (pageIndex + 1);
searchHistory.pageSize = pageSize;
searchHistory.sortField = sortBy.length > 0 ? sortBy[0].id : null;
searchHistory.sortOrder = sortBy.length > 0 ? sortBy[0].desc ? 'desc' : 'asc' : null;
searchAction(searchHistory)
}
}, [pageIndex, sortBy, pageSize])
const paginationComponent = useMemo(() => {
let pagination = [];
let lado = 2;
// tamanho padrão
let startPage = pageIndex - lado;
let maxPage = pageIndex + lado;
// controle para enconstar nas pontas
if (startPage < 0) {
maxPage += -1 * startPage;
} else if (maxPage > pageCount - 1) {
startPage -= maxPage - pageCount + 1;
}
// limpeza de paginas extras
if (startPage < 0) {
startPage = 0;
}
if (maxPage > pageCount - 1) {
maxPage = pageCount - 1;
}
pagination.push( gotoPage(0)}>
first_page
);
pagination.push( previousPage()}>
chevron_left
);
for (let currentPage = startPage; currentPage
{currentPage + 1}
);
}
pagination.push( nextPage()}>
chevron_right
);
pagination.push( gotoPage(pageCount - 1)}>
last_page
);
return pagination;
}, [pageIndex, pageCount]);
// A function that sets the sorted value for the table
const setSortedValue = (column) => {
let sortedValue;
if (column.Header == null || (typeof column.Header != 'string')) {
sortedValue = false;
} else if (isSorted && column.isSorted) {
sortedValue = column.isSortedDesc ? "desc" : "asce";
} else {
sortedValue = "none";
}
return sortedValue;
};
// Setting the entries starting point
let entriesStart = searchResultData.total < 1 ? 0 : pageIndex * pageSize + 1;
let entriesEnd = ((pageIndex === pageOptions.length - 1) || (searchResultData?.total < pageSize)) ? searchResultData?.total : pageSize * (pageIndex + 1);
return (
{/* */}
{!!!hideHeader &&
{headerGroups.map((headerGroup, key) => (
{headerGroup.headers.map((column, key) => (
{column.Header != null && column.render("Header")}
))}
))}
}
{page.length === 0 ?
Nenhum Registro Encontrado
:
page.map((item, index) => {
prepareRow(item)
return (
{item.cells.map((cell) => (
buttonInRow(cell.row.original) : buttonInRow}
key={index}
noBorder={noEndBorder && rows.length - 1 === index}
align={cell.column.align ? cell.column.align : "left"}
{...cell.getCellProps()}
>
{cell.render("Cell")}
)
)}
);
})
}
{(!hideTotalEntries || pageCount > 1) &&
{!hideTotalEntries && (
{t('general.table.pagination', [entriesStart, entriesEnd, searchResultData.total])}
)}
{pageCount > 1 && (
{paginationComponent}
)}
}
{/* */}
);
}
Table7.defaultProps = {
initialPageSize: 10,
sizePerPage: { defaultValue: 10, sizes: [1, 5, 10, 15, 20, 25] },
paginationStyle: { variant: "gradient", color: "dark" },
isSorted: true,
noEndBorder: false,
searchResult: PropTypes.any.isRequired,
columns: PropTypes.array.isRequired,
isPaginationServer: false,
pageKeyMap: null,
buttonInRow: null,
hideHeader: false,
hideTotalEntries: false,
fullwidth: true,
rowClasses: null
};
Table7.propTypes = {
initialPageSize: PropTypes.number,
sizePerPage: PropTypes.oneOfType([
PropTypes.shape({
defaultValue: PropTypes.number,
sizes: PropTypes.arrayOf(PropTypes.number),
}),
]),
paginationStyle: PropTypes.shape({
variant: PropTypes.oneOf(["contained", "gradient"]),
color: PropTypes.oneOf([
"primary",
"secondary",
"info",
"success",
"warning",
"error",
"dark",
"light",
]),
}),
isSorted: PropTypes.bool,
noEndBorder: PropTypes.bool,
isPaginationServer: PropTypes.bool,
pageKeyMap: PropTypes.string,
buttonInRow: PropTypes.func,
hideHeader: PropTypes.bool,
hideTotalEntries: PropTypes.bool,
fullwidth: PropTypes.bool,
rowClasses: PropTypes.string,
};
< /code>
Все, что вам нужно, чтобы запустить ошибку, это не покинуть закомментированную часть. Я взял реализацию флажки непосредственно из документации
https://react-table-v7-docs.netlify.app ... nобразное/> , что вы попробовали-> Пользовательский выбор с выбором с помощью Selection с помощью Selection с помощью Selection. Флажок в таблице < /p>
Что на самом деле получило .-> Ошибка времени выполнения. Ошибка
: максимальная глубина обновления превышена. Это может произойти, когда компонент многократно вызывает Setstate Inside ComponentWillupDate или ComponentDidupDate. React ограничивает количество вложенных обновлений, чтобы предотвратить бесконечные петли.
Подробнее здесь: https://stackoverflow.com/questions/797 ... hen-adding
Таблица React с пользователями, которые выбрасывают «Максимальная глубина обновления превышенной» при добавлении столбца ⇐ Javascript
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение