Я пытаюсь следовать этой веб-статье, чтобы реализовать нумерацию страниц.
import React, { useState, useMemo } from "react";
import Config from 'config';
import { formatter } from '../common.js'
import { format } from 'date-fns';
import Pagination from '../Pagination';
import "./Order.css";
let PageSize = 25;
class Portal extends React.Component {
constructor() {
super();
this.state = {
name: 'React',
apiData: [],
};
}
async componentDidMount() {
console.log('app mounted');
const tokenString = sessionStorage.getItem("token");
const token = JSON.parse(tokenString);
let headers = new Headers({
"Accept": "application/json",
"Content-Type": "application/json",
'Authorization': 'Bearer ' + token.token
});
const response = await fetch(Config.apiUrl + `/api/Orders/GetAllInvoices`, {
method: "GET",
headers: headers
});
const json = await response.json();
console.log(json);
this.setState({ orderList: json });
}
render() {
const orders = this.state.orderList;
const [currentPage, setCurrentPage] = useState(1); <<== Error here
const currentTableData = useMemo(() => {
const firstPageIndex = (currentPage - 1) * PageSize;
const lastPageIndex = firstPageIndex + PageSize;
return orders.slice(firstPageIndex, lastPageIndex);
}, [currentPage]);
return (
<div>
<h2>Portal</h2>
<br />
<h3>Past Orders</h3>
<table className="table table-striped table-bordered">
<thead>
<tr>
<th className="number">Invoice Number</th>
<th className="date">Invoice Date</th>
<th className="amount">Amount</th>
</tr>
</thead>
<tbody>
{currentTableData && currentTableData.map(order =>
<tr key={order.sopnumbe}>
<td>{order.sopnumbe}</td>
<td>{format(Date.parse(order.docdate), 'MM/dd/yyyy')}</td>
<td>{formatter.format(order.docamnt)}</td>
</tr>
)}
</tbody>
</table>
<Pagination
className="pagination-bar"
currentPage={currentPage}
totalCount={orders.length}
pageSize={PageSize}
onPageChange={page => setCurrentPage(page)}
/>
</div>
);
}
}
export default Portal;
Поскольку это компонент класса, я получаю сообщение об ошибке "Недопустимый вызов ловушки" при попытке useHook
внутри компонента класса, как указано здесь.
Я попытался переместить это во внешнюю функцию и вызвать foo()
внутри моего рендера:
import React, { useState, useMemo } from "react";
import Config from 'config';
import { formatter } from '../common.js'
import { format } from 'date-fns';
import Pagination from '../Pagination';
import "./Order.css";
let PageSize = 25;
function foo() {
const [currentPage, setCurrentPage] = useState(1);
}
...
Но теперь, что мне нужно сделать, чтобы получить доступ к currentPage
и setCurrentPage
внутри моей функции рендеринга, добавить this.
или переместить строку const [currentPage, setCurrentPage] = useState(1)
в componentDidMount
?
Компоненты класса не поддерживают хуки. Если вы хотите использовать хуки (
useState
,useEffect
..), вы можете начать с написания нового кода в виде функциональных компонентов с хуками. Вы можете прочитать больше о Hooks-FAQ здесь.