【发布时间】:2021-08-09 02:17:13
【问题描述】:
我正在尝试关注this网络文章来实现分页。
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 时收到错误“无效的钩子调用”,如提到的 here。
我已尝试将其移至外部函数并在我的渲染中调用 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 的更多信息here。
标签: javascript reactjs pagination