reactjs setState不会在next.js中实现状态更改

0sgqnhkj  于 2023-11-18  发布在  React
关注(0)|答案(2)|浏览(158)

我尝试使用setCurrentPage(page)更改页码,但当我单击按钮时,状态根本没有改变。尝试了不同的方法,但都不起作用。
我尝试手动更改useState(1)中的数字,并验证了页面更改。

import axios from "axios";
import { useEffect, useState } from "react";
import '../css/page.css';
import '../css/sermons.css';
import SermonModal from "./SermonModal";
import Pagination from '@mui/material/Pagination';
import Stack from "@mui/material/Stack";
import Pagenation from "./Pagenation";

export default function GetAllSermon() {

    const [sermon, setSermon] = useState({});
    const [isLoading, setIsLoading] = useState(true);
    const [currentPosts, setCurrentPosts] = useState([]);
    const [currentPage, setCurrentPage] = useState(1);
    const [postsPerPage, setPostsPerPage] = useState(3);

    const lastPostIndex = currentPage * postsPerPage;
    const firstPostIndex = lastPostIndex - postsPerPage;

    useEffect(() => {
        axios.get(`${process.env.NEXT_PUBLIC_SERVER_URL}/sermons`)
            .then((response) => {
                setCurrentPosts(response.data.sermons.toReversed().slice(firstPostIndex, lastPostIndex));
                setSermon(response.data.sermons.toReversed());
                setIsLoading(false);
            })
            .catch((err) => {
                console.log(err);
            });
    }, []);

    const pages = [];

    for (let i = 1; i <= Math.ceil(sermon.length / postsPerPage); i++) {
        pages.push(i);
    }

    if (isLoading) return <div>Loading...</div>;

    return (
        <>
            {currentPosts.map((sermon) => (
                <div className="component_sermon_section" key={sermon._id}>
                    <div className="sermon_snap">
                        <a href='#'><img src={sermon.snap} className='sermon_snap' /></a>
                    </div>
                    <div className="sermon_info" >
                        <h3>
                            <SermonModal sermon={sermon} />
                        </h3>
                        <p className='date_time'>
                            {sermon.date.split('T')[0]} @ {sermon.session === 'First' ? '8:00 AM 
                                           1부' : null ||
                                sermon.session === 'Second' ? '09:30 AM 2부' : null ||
                                    sermon.session === 'Third' ? '11:00 AM 3부' : null} -
                                                        {sermon.preacher} 목사
                        </p>
                    </div>
                </div>))}
            {
                pages.map((page, index) => {
                    return (
                        <>
                            <button key={index} onClick={() => setCurrentPage(page)}>{page}
                            </button>
                        </>
                    );
                })
            }
        </>
    );
};;

字符串
尝试将当前页面设置为不同的页码,但不起作用。希望它更改当前页面的状态。

yyyllmsg

yyyllmsg1#

在创建组件时,您只计算一次firstPostIndex和lastPostIndex,但实际上您希望在每次状态更改时重新计算它们,因此您需要在useEffect中计算它们。

const lastPostIndex = currentPage * postsPerPage;
const firstPostIndex = lastPostIndex - postsPerPage;

字符串
在使用效果上。

useEffect(() => {
    const lastPostIndex = currentPage * postsPerPage;
    const firstPostIndex = lastPostIndex - postsPerPage;

    axios.get(`${process.env.NEXT_PUBLIC_SERVER_URL}/sermons`)
            .then((response) => {
                setCurrentPosts(response.data.sermons.toReversed().slice(firstPostIndex, lastPostIndex));
                setSermon(response.data.sermons.toReversed());
                setIsLoading(false);
            })
            .catch((err) => {
                console.log(err);
            });
}, []);

tzxcd3kk

tzxcd3kk2#

useEffect(() => {

const lastPostIndex = currentPage * postsPerPage;
const firstPostIndex = lastPostIndex - postsPerPage

            axios.get(`${process.env.NEXT_PUBLIC_SERVER_URL}/sermons`)
                .then((response) => {
setCurrentPosts(response.data.sermons.toReversed().slice(firstPostIndex, lastPostIndex));
                setSermon(response.data.sermons.toReversed());
                setIsLoading(false);
            })
            .catch((err) => {
                console.log(err);
            });
    }, [currentPage]);

字符串
很可能curretPage正在更新,但由于useEffect没有更新,因此情况没有改变。请尝试使用这种方式使用useEffect。如果没有,请检查page变量是否为number。请报告结果。

相关问题