react的函数式编程分页的时候还有查询条件,当翻页或者有查询条件的时候去调用接口,查询条件是个对象,如何实现,具体的代码

复制代码
import React, { useState, useEffect } from 'react';
import axios from 'axios';

const API_BASE_URL = 'https://api.example.com/data';

const MyComponent = () => {
  const [data, setData] = useState([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [query, setQuery] = useState({ keyword: '', category: '' });

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.get(`${API_BASE_URL}`, {
          params: {
            page: currentPage,
            keyword: query.keyword,
            category: query.category,
          },
        });
        setData(response.data.results);
        setTotalPages(response.data.totalPages);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };

    fetchData();
  }, [currentPage, query]);

  const handlePageChange = (newPage) => {
    setCurrentPage(newPage);
  };

  const handleQueryChange = (field, value) => {
    setQuery((prevQuery) => ({
      ...prevQuery,
      [field]: value,
    }));
  };

  return (
    <div>
      <input
        type="text"
        value={query.keyword}
        onChange={(e) => handleQueryChange('keyword', e.target.value)}
        placeholder="Enter keyword"
      />
      <input
        type="text"
        value={query.category}
        onChange={(e) => handleQueryChange('category', e.target.value)}
        placeholder="Enter category"
      />

      <ul>
        {data.map((item) => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>

      <div>
        <button onClick={() => handlePageChange(currentPage - 1)} disabled={currentPage === 1}>
          Previous
        </button>
        <span>Page {currentPage} of {totalPages}</span>
        <button onClick={() => handlePageChange(currentPage + 1)} disabled={currentPage === totalPages}>
          Next
        </button>
      </div>
    </div>
  );
};

export default MyComponent;

ts

复制代码
import React, { useState, useEffect } from 'react';
import axios from 'axios';

interface Item {
  id: number;
  name: string;
  // 添加其他属性
}

interface ApiResponse {
  results: Item[];
  totalPages: number;
}

interface Query {
  keyword: string;
  category: string;
  // 添加其他查询条件
}

const API_BASE_URL = 'https://api.example.com/data';

const MyComponent: React.FC = () => {
  const [data, setData] = useState<Item[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [query, setQuery] = useState<Query>({ keyword: '', category: '' });

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.get<ApiResponse>(API_BASE_URL, {
          params: {
            page: currentPage,
            keyword: query.keyword,
            category: query.category,
          },
        });
        setData(response.data.results);
        setTotalPages(response.data.totalPages);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };

    fetchData();
  }, [currentPage, query]);

  const handlePageChange = (newPage: number) => {
    setCurrentPage(newPage);
  };

  const handleQueryChange = (field: keyof Query, value: string) => {
    setQuery((prevQuery) => ({
      ...prevQuery,
      [field]: value,
    }));
  };

  return (
    <div>
      <input
        type="text"
        value={query.keyword}
        onChange={(e) => handleQueryChange('keyword', e.target.value)}
        placeholder="Enter keyword"
      />
      <input
        type="text"
        value={query.category}
        onChange={(e) => handleQueryChange('category', e.target.value)}
        placeholder="Enter category"
      />

      <ul>
        {data.map((item) => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>

      <div>
        <button onClick={() => handlePageChange(currentPage - 1)} disabled={currentPage === 1}>
          Previous
        </button>
        <span>Page {currentPage} of {totalPages}</span>
        <button onClick={() => handlePageChange(currentPage + 1)} disabled={currentPage === totalPages}>
          Next
        </button>
      </div>
    </div>
  );
};

export default MyComponent;

在这个示例中,Item 表示每个数据项的类型,ApiResponse 表示 API 返回的数据类型,Query 表示查询条件的类型。使用 TypeScript 可以提供更好的类型检查,确保代码的稳定性。

相关推荐
温轻舟3 分钟前
禁毒路上,任重道远 | HTML页面
开发语言·前端·javascript·css·html·温轻舟
likuolei22 分钟前
XSL-FO 列表
前端·数据库
shaohaoyongchuang23 分钟前
vue_03路由
前端·javascript·vue.js
我叫张小白。30 分钟前
Vue3计算属性:高效数据处理
前端·javascript·vue.js·前端框架·vue
e***749544 分钟前
【JavaEE】Spring Web MVC
前端·spring·java-ee
AntBlack1 小时前
Z-Image 发布了 ,赶紧体验了一把(配套 Modal执行脚本)
前端·后端·aigc
●VON1 小时前
Electron 项目在“鸿蒙端”与“桌面端”运行的区别
javascript·学习·electron·openharmony
诸葛韩信1 小时前
前端工程化1——npm insatall背后的工作原理
前端·npm·node.js
徐小夕@趣谈前端1 小时前
NO-CRM本地安装版开源!人人都能拥有开箱即用的智慧CRM管理系统
javascript·vue.js·开源
箫笙默2 小时前
JS基础 - 正则笔记
开发语言·javascript·笔记