永年網(wǎng)站建設(shè)競價推廣開戶
問題:
1.使用useState時不能夠進行當前頁碼的改變,數(shù)據(jù)不會隨著頁碼變化
2.刪除當前頁的最后一條數(shù)據(jù)時,頁碼返回上一頁但是數(shù)據(jù)為空
解決:
1.由于useState和useRef的區(qū)別那我們就不考慮使用useState
2.再刪除的邏輯當中添加判斷條件
import React, { useRef } from 'react';
import { Pagination } from 'antd';const YourComponent = () => {const currentPageRef = useRef(1); // 使用 useRef 來保存當前頁碼 可以為空const handlePageChange = (page) => {console.log(page, 'pageeeee');getMessage(page);currentPageRef.current = page; // 更新當前頁碼};const handleDelete = (id) => {// 執(zhí)行刪除操作// 刪除成功后,判斷當前頁是否還有數(shù)據(jù)// 如果沒有數(shù)據(jù)且不是第一頁,則回退到上一頁if (data.length === 1 && currentPageRef.current > 1) {const newPage = currentPageRef.current - 1; // 計算上一頁的頁碼getMessage(newPage); // 獲取上一頁的數(shù)據(jù)currentPageRef.current = newPage; // 更新當前頁碼為上一頁} else {getMessage(currentPageRef.current); // 否則重新請求當前頁的數(shù)據(jù)}};return (<div>{/* 省略其他內(nèi)容 */}<PaginationonChange={handlePageChange}current={currentPageRef.current}// 其他配置項.../></div>);
};export default YourComponent;
補充:
react中useState、useRef之間的區(qū)別
- useState:
const [state, setState] = useState(0)
const fn = () => {setState(1)console.log(state) //輸出0
}
組件更新不會改變之前的狀態(tài),可以保存狀態(tài)。
值變化,會render,視圖會更新。
setState是異步的,同一個函數(shù)內(nèi)設(shè)置的,不能實時獲取到最新的值。
- useRef:
const num = useRef(0)
const fn = () => {num.current = 1console.log(num.current) //輸出1
}
組件更新不會改變之前的狀態(tài),可以保存狀態(tài)。
值變化,不會render,視圖不會更新。
設(shè)置的值是同步的,同一個函數(shù)內(nèi)設(shè)置的,能實時獲取到最新的值。