【问题标题】:Button is not displaying correctly in ReactJSReactJS 中的按钮显示不正确
【发布时间】:2020-06-18 09:58:29
【问题描述】:

我正在尝试为我的网页进行分页,我已将限制设置为每页 10 个项目。 问题是每当我添加第 11 项时,新页面按钮都不会显示,仅在我添加第 12 项后才会出现。

有什么建议吗?

添加功能:

    addItem = () => {
        const {addItems, setPageCount} = this.props.actions;
        let userName = localStorage.getItem('username')

        if (this.inpRef.current.value === '') {
            return alert('We dont do that here....')
        } else {
            axios
                .post(`http://localhost:8080/add`, {
                    username: userName,
                    todo: this.inpRef.current.value,
                    checked: false,
                })
                .then((res) => {
                    const {todo, checked, _id} = res.data;
                    addItems(todo, checked, _id);
                    console.log('res', res)
                })
                .catch((err) => {
                    console.log("err", err);
                });
            this.inpRef.current.value = "";
            setPageCount()

        }
    }

在渲染中切片:

    const {todos, currentPage, itemsPerPage} = this.props;
    const indexOfLastItem = currentPage * itemsPerPage;
    const indexOfFirstItem = indexOfLastItem - itemsPerPage;
    const currentItems = todos.slice(indexOfFirstItem, indexOfLastItem);

setPageCount 函数:

    case actionTypes.PAGE_COUNT:
    const setPageCount =  Math.ceil(todos.length / 10 )
    return {
        ...state,
        pageCount: setPageCount
    }

【问题讨论】:

  • 看看我添加的答案。谢谢
  • 成功了,非常感谢,如果需要,可以将其添加到答案中,以便我投票并接受答案

标签: javascript reactjs button


【解决方案1】:

为什么要在const setPageCount = Math.ceil(todos.length / 10 ) + 1 处添加额外的 1。我认为您应该使用floor 而不是ceil。如您所见,您是否有 1 个待办事项。 Math.ceil(1/10) + 1 = 2 这意味着您只有 1 个项目,但您正在显示 2 个页面。

【讨论】:

    【解决方案2】:

    它将异步工作,因此使用 promiseasync/await 使其同步。

    下面的这个链接包含关于异步的文档。

    Click this

    希望这对您的过程有所帮助。

    【讨论】:

      猜你喜欢
      • 2014-04-08
      • 2015-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-01
      • 2020-12-09
      • 2013-08-22
      相关资源
      最近更新 更多