React点击替换变量值问题:TMDB API电影生成器类型筛选异常
It sounds like the core issue here is that your variable storing excluded genre IDs isn’t being reset when the user switches to a new target genre—instead of replacing the old value, you’re appending new IDs to it, which makes the API exclude way more genres than intended. Let’s fix that:
Root Cause
When you first set up your excluded IDs for the initial genre, it works correctly. But when the user picks a new genre, you’re probably doing something like excludedIds += newExcludedIds instead of overwriting the variable with a fresh set of excluded IDs tailored to the new selection.
Solution: Reset & Recalculate on Genre Switch
Every time the user selects a new target genre, recalculate the excluded IDs from scratch (all genres except the selected one) and assign this new list directly to your variable—don’t append to the old value.
Here’s a concrete example using Axios and JavaScript:
- First, cache all possible genre IDs (fetch this once from TMDB’s genre list endpoint and store it):
// Assume you've fetched and stored all TMDB genres here const allGenres = [ { id: 28, name: "Action" }, { id: 35, name: "Comedy" }, { id: 18, name: "Drama" }, // ... add all other genres from TMDB's API response ];
- Create a handler for genre selection:
let excludedGenreIds = ""; // Initialize empty function handleGenreSelect(selectedGenreId) { // Calculate excluded IDs: all genre IDs except the selected target const freshExcludedIds = allGenres .filter(genre => genre.id !== selectedGenreId) .map(genre => genre.id) .join(","); // Convert to comma-separated string as TMDB expects // Replace the old value entirely (critical step!) excludedGenreIds = freshExcludedIds; // Now fetch a movie with the updated excluded IDs fetchRandomMovie(); } function fetchRandomMovie() { axios.get("https://api.themoviedb.org/3/discover/movie", { params: { api_key: "YOUR_API_KEY", without_genres: excludedGenreIds, // Uses the fresh, non-stacked IDs sort_by: "popularity.desc", include_adult: false // Add other params as needed } }) .then(response => { // Handle your random movie result here console.log("Random movie:", response.data.results[0]); }) .catch(error => { console.error("Error fetching movie:", error); }); }
Key Takeaway
By recalculating excludedGenreIds from scratch and assigning it directly (not appending) every time the user switches genres, you ensure the API only receives the correct set of excluded genres for the current selection. This eliminates the stacking issue entirely.
If you were previously using code like excludedGenreIds += "," + newIds, replacing that with a full reassignment is the fix you need.
内容的提问来源于stack exchange,提问作者Designbysite

