这是对我上一个问题的跟进。请参阅:How to keep the current state of a page after a refresh? - React
const PAGE_SIZE: number = 10;
const PAGE_KEY = "currentPage";
//SEE ANSWER OF THE QUESTION I LINKED TO SEE WHY I WANT TO USE THIS FUNCTION HERE
const getPageNumber = () => {
if (
sessionStorage &&
parseInt(String(sessionStorage.getItem(PAGE_KEY))) > 0
) {
return parseInt(String(sessionStorage.getItem(PAGE_KEY)));
}
return 1;
};
type State = {
handleCheck: Record<string, boolean>;
currentPage: number;
};
const initialState: State = {
handleCheck: { Skipped: false, Live: false },
currentPage: 1,
};
interface toggleFilterAction {
type: "toggle";
payload: string;
}
interface incrementPageAction {
type: "incrementPage";
}
interface decrementPageAction {
type: "decrementPage";
}
interface setPageAction {
type: "setPage";
nextPage: number;
}
export type Actions =
| toggleFilterAction
| incrementPageAction
| decrementPageAction
| setPageAction;
function reducer(state: State, action: Actions): State {
switch (action.type) {
case "toggle":
... for toggling filters
case "incrementPage":
const nextPage = Math.min(state.currentPage + 1);
return {
...state,
currentPage: nextPage,
};
case "decrementPage":
if (state.currentPage === 1) {
return state;
}
const prevPage = state.currentPage - 1;
return {
...state,
currentPage: prevPage,
};
case "setPage":
return {
...state,
currentPage: action.nextPage,
};
default:
return state;
}
}
export const SuitesPage: React.FC<{}> = () => {
const [state, dispatch] = React.useReducer(reducer, initialState);
const suitesForProject = ... data from array and some filtering happens here;
const totalPages = suitesForProject.length
? Math.ceil(suitesForProject.length / PAGE_SIZE)
: 0;
const handleClickNext = () => {
if (!suitesForProject.length) {
return;
}
dispatch({ type: "incrementPage" });
};
const handleClickPrev = () => {
if (!suitesForProject.length) {
return;
}
dispatch({ type: "decrementPage" });
};
const handleClickIndex = (e) => {
if (!suitesForProject.length) {
return;
}
dispatch({ type: "setPage", nextPage: e.goToPage });
};
return (
<>
<Filters
...some filters buttons are here
/>
{suitesForProject
.slice(
(state.currentPage - 1) * PAGE_SIZE,
PAGE_SIZE * state.currentPage,
)
.map((suitesForProject) => (
...doing stuff with data from array
))}
<Pagination
currentPage={state.currentPage}
totalPages={totalPages}
onClickIndex={handleClickIndex}
onClickPrevious={handleClickPrev}
onClickNext={handleClickNext}
/>
</>
);
};
对于我的“incrementPage”、“decrement”和“setPage”操作,我想使用 sessionStorage 从状态中保存当前页面。
我之前的问题得到了很好的回答。我想通过对 useReducer 做同样的事情来跟进。