import React, { useState, useEffect, useContext } from 'react'; import axios from 'axios'; import Container from '@mui/material/Container'; import Grid from '@mui/material/Grid'; import Card from '@mui/material/Card'; import CardMedia from '@mui/material/CardMedia'; import CardContent from '@mui/material/CardContent'; import Typography from '@mui/material/Typography'; import Pagination from '@mui/material/Pagination'; import { Link } from 'react-router-dom'; import CircularProgress from '@mui/material/CircularProgress'; import ConfigContext from './Config'; import MovieCard from './MovieCard'; import CategoryNav from './CategoryNav'; const Main = () => { const config = useContext(ConfigContext); const [currentCategory, setCurrentCategory] = useState(0); const categories = [ { label: '15min', idx: 0 }, { label: '30min', idx: 1 }, { label: '60min', idx: 2 }, { label: '大于60min', idx: 3 }, ]; const [pagination, setPagination] = useState({ movies: [], page: 1, total: 1, length: 1, }); const [loading, setLoading] = useState(false); const limit = 20; const handleCategoryChange = (category) => { setCurrentCategory(category); fetchMovies(category, 1); }; const fetchMovies = async (category, page) => { setLoading(true); try { const response = await axios.get( `${config.Host}/movie/?page=${page}&limit=${limit}&category=${category}` ); if (response.status === 200) { const data = response.data.data; console.log(`${config.Host}/movie/?page=${page}&limit=${limit}&category=${category}`); if (data.items.length === 0 && page > 1) { // 如果返回的数据为空且请求的页码大于1,则尝试获取上一页的数据 fetchMovies(page - 1); } else { setPagination({ movies: data.items, page: page, total: data.total, length: Math.ceil(data.total / limit), }); localStorage.setItem('lastPage', page); } } } catch (error) { console.error('Error fetching movies:', error); } finally { setLoading(false); } }; useEffect(() => { const lastPage = localStorage.getItem('lastPage') || 1; fetchMovies(currentCategory, lastPage); }, []); const handlePageChange = (event, value) => { fetchMovies(currentCategory, value); }; const truncateFilename = (filename, maxLength) => { return filename.length > maxLength ? filename.substring(0, maxLength - 3) + '...' : filename; }; return (
{loading ? (
) : ( {pagination.movies.map((item) => ( ))} )}
); }; export default Main;