x-movie/src/Main.jsx

210 lines
6.2 KiB
React
Raw Normal View History

2025-06-02 03:19:36 +08:00
import React, { useState, useEffect, useContext, useCallback, useRef } from 'react';
2023-07-04 23:47:01 +08:00
import axios from 'axios';
import Container from '@mui/material/Container';
import Grid from '@mui/material/Grid';
import Pagination from '@mui/material/Pagination';
import { Link } from 'react-router-dom';
2023-07-05 01:33:55 +08:00
import CircularProgress from '@mui/material/CircularProgress';
2023-07-04 23:47:01 +08:00
2023-07-08 17:44:51 +08:00
import ConfigContext from './Config';
2023-07-09 05:58:33 +08:00
import MovieCard from './components/MovieCard';
import CategoryNav from './components/CategoryNav';
2023-07-04 23:47:01 +08:00
2025-06-02 03:19:36 +08:00
const categories = [
{ label: '15min', value: '15min' },
{ label: '30min', value: '30min' },
{ label: '60min', value: '60min' },
{ label: '大于60min', value: '大于60min' },
];
const LIMIT = 20;
const usePersistedState = (key, defaultValue) => {
const [state, setState] = useState(() => {
const stored = localStorage.getItem(key);
return stored ? JSON.parse(stored) : defaultValue;
});
useEffect(() => {
localStorage.setItem(key, JSON.stringify(state));
}, [key, state]);
return [state, setState];
};
2024-03-28 03:40:13 +08:00
const Main = () => {
const config = useContext(ConfigContext);
const [loading, setLoading] = useState(false);
2025-06-02 03:19:36 +08:00
const scrollRef = useRef(0);
// 初始化状态,直接使用 categories 中的 value 值
const [params, setParams] = usePersistedState('params', {
lastCategory: categories[0].value, // 直接使用 '15min' 这样的值
history: categories.reduce((acc, category) => ({
...acc,
[category.value]: { lastPage: 1, scrollPos: 0 } // 使用 category.value 作为键
}), {})
2024-03-28 03:40:13 +08:00
});
2023-07-04 23:47:01 +08:00
2025-06-02 03:19:36 +08:00
const [movies, setMovies] = useState([]);
const [pagination, setPagination] = useState({ page: 1, total: 0, pages: 1 });
const fetchMovies = useCallback(async (category, page) => {
2024-03-28 03:40:13 +08:00
setLoading(true);
2023-07-04 23:47:01 +08:00
try {
2025-06-02 03:19:36 +08:00
// 直接使用 category 值,不需要转换
2023-07-04 23:47:01 +08:00
const response = await axios.get(
2025-06-02 03:19:36 +08:00
`/movie/?page=${page}&limit=${LIMIT}&category=${encodeURIComponent(category)}`
2023-07-04 23:47:01 +08:00
);
2023-07-09 11:30:56 +08:00
2023-07-04 23:47:01 +08:00
if (response.status === 200) {
2025-06-02 03:19:36 +08:00
const { items, total } = response.data.data;
if (items.length === 0 && page > 1) {
setParams(prev => ({
...prev,
history: {
...prev.history,
[category]: {
...(prev.history[category] || { lastPage: 1, scrollPos: 0 }),
lastPage: page - 1
}
}
}));
return;
2023-07-08 17:44:51 +08:00
}
2025-06-02 03:19:36 +08:00
setMovies(items);
setPagination({
page,
total,
pages: Math.ceil(total / LIMIT)
});
requestAnimationFrame(() => {
window.scrollTo(0, scrollRef.current);
});
2023-07-04 23:47:01 +08:00
}
} catch (error) {
console.error('Error fetching movies:', error);
2023-07-05 01:33:55 +08:00
} finally {
2024-03-28 03:40:13 +08:00
setLoading(false);
2023-07-04 23:47:01 +08:00
}
2025-06-02 03:19:36 +08:00
}, [setParams]);
const getCurrentCategoryAndPage = useCallback(() => {
// 直接从 params 中获取 lastCategory确保它是 categories 中的 value 值
const lastCategory = params.lastCategory || categories[0].value;
const categoryHistory = params.history[lastCategory] || { lastPage: 1, scrollPos: 0 };
return {
category: lastCategory,
page: categoryHistory.lastPage
};
}, [params]);
2023-07-04 23:47:01 +08:00
useEffect(() => {
2025-06-02 03:19:36 +08:00
const { category, page } = getCurrentCategoryAndPage();
scrollRef.current = params.history[category]?.scrollPos || 0;
fetchMovies(category, page);
}, [getCurrentCategoryAndPage, fetchMovies, params.history]);
const handleCategoryChange = useCallback((category) => {
scrollRef.current = window.scrollY;
const currentCategory = params.lastCategory || categories[0].value;
setParams(prev => {
const newHistory = {
...prev.history,
[currentCategory]: {
...(prev.history[currentCategory] || { lastPage: 1, scrollPos: 0 }),
scrollPos: scrollRef.current
2024-03-28 03:40:13 +08:00
},
2025-06-02 03:19:36 +08:00
[category]: {
...(prev.history[category] || { lastPage: 1, scrollPos: 0 })
}
};
2025-06-02 03:19:36 +08:00
return {
...prev,
lastCategory: category, // 直接存储传入的 category 值
history: newHistory
};
});
}, [params.lastCategory, setParams]);
2023-07-10 00:50:11 +08:00
2025-06-02 03:19:36 +08:00
const handlePageChange = useCallback((_, page) => {
scrollRef.current = window.scrollY;
const lastCategory = params.lastCategory || categories[0].value;
2023-07-10 00:50:11 +08:00
2025-06-02 03:19:36 +08:00
setParams(prev => ({
...prev,
2024-03-28 03:40:13 +08:00
history: {
2025-06-02 03:19:36 +08:00
...prev.history,
[lastCategory]: {
...(prev.history[lastCategory] || { lastPage: 1, scrollPos: 0 }),
lastPage: page
}
}
}));
}, [params.lastCategory, setParams]);
const handleMovieCardClick = useCallback(() => {
scrollRef.current = window.scrollY;
const lastCategory = params.lastCategory || categories[0].value;
setParams(prev => ({
...prev,
history: {
...prev.history,
[lastCategory]: {
...(prev.history[lastCategory] || { lastPage: 1, scrollPos: 0 }),
scrollPos: scrollRef.current
}
}
}));
}, [params.lastCategory, setParams]);
2023-07-04 23:47:01 +08:00
return (
2023-07-08 03:15:48 +08:00
<Container style={{ marginTop: 20 }}>
2023-07-09 11:30:56 +08:00
<CategoryNav
2024-03-28 03:40:13 +08:00
categories={categories}
2025-06-02 03:19:36 +08:00
currentCategory={params.lastCategory || categories[0].value}
2023-07-09 11:30:56 +08:00
onCategoryChange={handleCategoryChange}
/>
2025-06-02 03:19:36 +08:00
<Pagination
count={pagination.pages}
page={pagination.page}
onChange={handlePageChange}
sx={{ my: 2, display: 'flex', justifyContent: 'center' }}
/>
2024-03-28 03:40:13 +08:00
{loading ? (
2025-06-02 03:19:36 +08:00
<CircularProgress sx={{ display: 'block', margin: '20px auto' }} />
) : (
2025-06-02 03:19:36 +08:00
<Grid container spacing={2} sx={{ mt: 0.5 }}>
{movies.map((item) => (
<Grid item xs={6} sm={4} md={3} lg={2} key={item.filename}>
<Link
to={`/res/${item.filename}`}
style={{ textDecoration: 'none', paddingBottom: 10 }}
onClick={handleMovieCardClick}
>
<MovieCard movie={item} config={config} />
</Link>
</Grid>
))}
</Grid>
)}
2025-06-02 03:19:36 +08:00
<Pagination
count={pagination.pages}
page={pagination.page}
onChange={handlePageChange}
sx={{ my: 2, display: 'flex', justifyContent: 'center' }}
/>
2023-07-04 23:47:01 +08:00
</Container>
);
};
export default Main;