页面导航数字为什么在我的React代码中无法正常工作?

huangapple go评论72阅读模式
英文:

Why page navigation numbers are not working correctly in my React Code?

问题

我怀疑这一行出现了问题:

{Array.from({length: totalPages+1}, (_, i) => i)
    .slice(selectedPageNumber <= 5 ? 1 : selectedPageNumber - 5, selectedPageNumber < 5 ? 10 : selectedPageNumber + 6)
}

当我在最后的按钮上调用changeSelectedPageNumber()函数时,可能我遗漏了一些东西。

我在哪里犯了错误?

如果我理解得正确,您的问题是关于页面导航数字显示的问题。您希望在输入页数后,页面导航数字能够正确显示。

在上述代码中,selectedPageNumber 表示当前选定的页数,而 totalPages 表示总页数。这段代码的目的是生成一个包含导航数字的数组,以便在页面上显示导航按钮。

首先,它使用 Array.from 创建了一个包含数字的数组,从1到 totalPages。然后,使用 .slice 方法根据 selectedPageNumber 的值截取需要显示的部分。

问题可能出在 slice 方法的参数上。如果 selectedPageNumber 小于或等于5,它截取的范围是从1到10。但如果 selectedPageNumber 大于5,它截取的范围可能会超出总页数。

为了修复问题,您可以尝试修改这段代码,以确保 slice 方法不会截取超出范围的部分。您可以使用 Math.minMath.max 函数来限制截取范围,如下所示:

{Array.from({length: totalPages}, (_, i) => i + 1)
    .slice(Math.max(1, selectedPageNumber - 5), Math.min(totalPages, selectedPageNumber + 6))
}

这将确保 slice 方法不会截取超出总页数范围的部分,同时保持导航按钮的显示正确。希望这对您有所帮助。

英文:

I do not like questions like "Why code is not working?" but I cannot find solution to my problem. I have a react component including a table and pagination numbers as follow:
页面导航数字为什么在我的React代码中无法正常工作?

Pagination numbers are working good but my problem is that, when I navigate to specific page by entering Page number into input field, and if it is more than 5 then the numbers 1,2,3,4,5,6... going too much as follows:
页面导航数字为什么在我的React代码中无法正常工作?

Here is my code:

import React, {useState, useEffect} from &quot;react&quot;;
import Table from &#39;react-bootstrap/Table&#39;;
import Pagination from &#39;react-bootstrap/Pagination&#39;;
import &#39;bootstrap/dist/css/bootstrap.min.css&#39;;
import * as cityService from &quot;../service/CityService&quot;;
import Button from &quot;react-bootstrap/Button&quot;;
import {useNavigate} from &quot;react-router-dom&quot;;
import HeaderPanel from &quot;./HeaderPanel&quot;;

function CityTable() {
    const [selectedPageNumber, setSelectedPageNumber] = useState(1);
    const [perPage, setPerPage] = useState(5);
    const [totalElement, setTotalElement] = useState(0);
    const [currentData, setCurrentData] = useState([]);
    const [pageNavigationNumber, setPageNavigationNumber] = useState(1);
    const [cityName, setCityName] = useState(&#39;&#39;);

    const totalPages = Math.ceil(totalElement / perPage);
    let navigate = useNavigate();


    const changeSelectedPageNumber = (pageNumber) =&gt; {

        // setPageNavigationNumber(pageNumber);
        setSelectedPageNumber(pageNumber);
    };

    const changePageSize = (event) =&gt; {
        const newPerPage = parseInt(event.target.value, 10);
        setSelectedPageNumber(1);
        setPerPage(newPerPage);
    };

    const findCities = async (cityName) =&gt; {
        let result = await cityService.getCityPage(cityName, selectedPageNumber - 1, perPage, sessionStorage.getItem(&#39;jwtToken&#39;));
        setCurrentData(result.data.content);
        setTotalElement(result.data.totalElements);
    };

    const handleRowClick = (item) =&gt; {
        sessionStorage.setItem(&#39;id&#39;, item.id);
        sessionStorage.setItem(&#39;cityname&#39;, item.name);
        sessionStorage.setItem(&#39;photo&#39;, item.photo);
        navigate(&quot;/details&quot;)

    }

    const addDefaultSrc = (ev) =&gt;
    {
        ev.target.src = require(&#39;../assets/nophoto.png&#39;);
    }

    useEffect(() =&gt; {
        findCities(cityName, selectedPageNumber, perPage);
    }, [selectedPageNumber, perPage]);

    return (
        &lt;div&gt;
            &lt;HeaderPanel&gt;&lt;/HeaderPanel&gt;
            &lt;input type={&quot;search&quot;}
                   placeholder={&quot;Search City&quot;}
                   onChange={e =&gt; setCityName(e.target.value)}
            &gt;&lt;/input&gt;
            &lt;Button onClick={() =&gt; findCities(cityName, selectedPageNumber, perPage)}&gt;Search&lt;/Button&gt;
            &lt;Table striped bordered hover&gt;
                &lt;thead&gt;
                &lt;tr&gt;
                    &lt;th&gt;ID&lt;/th&gt;
                    &lt;th&gt;Name&lt;/th&gt;
                    &lt;th&gt;Photo&lt;/th&gt;
                &lt;/tr&gt;
                &lt;/thead&gt;
                &lt;tbody&gt;
                {currentData.map((city) =&gt; (
                    &lt;tr key={city.id} onClick={() =&gt; handleRowClick(city)}&gt;
                        &lt;td&gt;{city.id}&lt;/td&gt;
                        &lt;td&gt;{city.name}&lt;/td&gt;
                        &lt;td&gt;&lt;img onError={addDefaultSrc} width={50} src={city.photo}/&gt;&lt;/td&gt;
                    &lt;/tr&gt;
                ))}
                &lt;/tbody&gt;
            &lt;/Table&gt;
            &lt;div className=&quot;d-flex justify-content-between align-items-center&quot;&gt;
                &lt;Pagination className=&quot;justify-content-lg-center&quot;&gt;
                    &lt;select value={perPage} onChange={changePageSize}&gt;
                        &lt;option value=&quot;5&quot;&gt;5&lt;/option&gt;
                        &lt;option value=&quot;10&quot;&gt;10&lt;/option&gt;
                        &lt;option value=&quot;15&quot;&gt;15&lt;/option&gt;
                    &lt;/select&gt;
                    &lt;Pagination.Prev
                        onClick={() =&gt; changeSelectedPageNumber(selectedPageNumber - 1)}
                        disabled={selectedPageNumber === 1}
                    /&gt;
                    {Array.from({length: totalPages+1}, (_, i) =&gt; i)
                        .slice(selectedPageNumber &lt;= 5 ? 1 : selectedPageNumber - 5, selectedPageNumber &lt; 5 ? 10 : selectedPageNumber + 6)
                        .map(page =&gt; (
                            &lt;Pagination.Item
                                key={page}
                                active={page === selectedPageNumber}
                                onClick={() =&gt; changeSelectedPageNumber(page)}
                            &gt;
                                {page}
                            &lt;/Pagination.Item&gt;

                        ))
                    }
                    &lt;Pagination.Next
                        onClick={() =&gt; changeSelectedPageNumber(selectedPageNumber + 1)}
                        disabled={selectedPageNumber === totalPages}
                    /&gt;
                &lt;/Pagination&gt;
            &lt;/div&gt;
            Page number:
            &lt;input type={&quot;number&quot;}
                   placeholder={&quot;Go to page&quot;}
                   value={pageNavigationNumber}
                   onChange={e =&gt; setPageNavigationNumber(e.target.value)}&gt;&lt;/input&gt;
            &lt;Button onClick={() =&gt; changeSelectedPageNumber(pageNavigationNumber)}&gt;Go to page&lt;/Button&gt;
        &lt;/div&gt;
    );
}

export default CityTable;

I am suspicious of the line:

{Array.from({length: totalPages+1}, (_, i) =&gt; i)
                        .slice(selectedPageNumber &lt;= 5 ? 1 : selectedPageNumber - 5, selectedPageNumber &lt; 5 ? 10 : selectedPageNumber + 6)

When I call changeSelectedPageNumber() function on button at last, maybe I am missing something.

Where am I making mistake?

答案1

得分: 1

每当您在输入字段中输入内容时,它都会被转换为字符串,这就是您在此处遇到问题的原因,您需要将输入从字符串转换为数字,然后进行数学计算。

您可以使用 parseInt+(缩写运算符)来将其转换为数字。

onChange={e => setPageNavigationNumber(+e.target.value)}></input>
英文:

Whenever you enter something in the input field, it is getting converting into string and that is why you are getting a problem here, you need to convert your input from string to number and do the Math calculation.

You can use parseInt or + (shortened operator) for converting into a number.

onChange={e =&gt; setPageNavigationNumber(+e.target.value)}&gt;&lt;/input&gt;

huangapple
  • 本文由 发表于 2023年2月27日 03:18:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/75574448.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定