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

2023-12-13 04:50:19
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 可以提供更好的类型检查,确保代码的稳定性。

文章来源:https://blog.csdn.net/m0_47999208/article/details/134813922
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。