• react中遇到的分页问题


    问题:
    1.使用useState时不能够进行当前页码的改变,数据不会随着页码变化
    2.删除当前页的最后一条数据时,页码返回上一页但是数据为空
    解决:
    1.由于useState和useRef的区别那我们就不考虑使用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) => {
        // 执行删除操作
        // 删除成功后,判断当前页是否还有数据
        // 如果没有数据且不是第一页,则回退到上一页
        if (data.length === 1 && currentPageRef.current > 1) {
          const newPage = currentPageRef.current - 1; // 计算上一页的页码
          getMessage(newPage); // 获取上一页的数据
          currentPageRef.current = newPage; // 更新当前页码为上一页
        } else {
          getMessage(currentPageRef.current); // 否则重新请求当前页的数据
        }
      };
    
      return (
        <div>
          {/* 省略其他内容 */}
          <Pagination
            onChange={handlePageChange}
            current={currentPageRef.current}
            // 其他配置项...
          />
        </div>
      );
    };
    
    export default YourComponent;
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38

    补充:

    react中useState、useRef之间的区别

    • useState:
    const [state, setState] = useState(0)
    const fn = () => {
    	setState(1)
    	console.log(state) //输出0
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    组件更新不会改变之前的状态,可以保存状态。
    值变化,会render,视图会更新。
    setState是异步的,同一个函数内设置的,不能实时获取到最新的值。

    • useRef:
    const num = useRef(0)
    const fn = () => {
    	num.current = 1
    	console.log(num.current) //输出1
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    组件更新不会改变之前的状态,可以保存状态。
    值变化,不会render,视图不会更新。
    设置的值是同步的,同一个函数内设置的,能实时获取到最新的值。

  • 相关阅读:
    当 AI 邂逅绘画艺术,能迸发出怎样的火花?
    python的/ 和// 学习
    系统封装制作
    上线项目问题——无法加载响应数据
    LCD电子手提秤电路板方案软硬件开发
    Kotlin的协程:flow
    elasticsearch-7.8.0 集群搭建
    c++入门必学算法 质数筛
    【golang】代理模式 proxy using in go
    vuex 中使用了modules,如何在页面中调用actions里面的方法
  • 原文地址:https://blog.csdn.net/m0_60676278/article/details/134266498