You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React分页组件搜索功能报错求助:Cannot read property 'length' of undefined

Hey there, let's work through that "Cannot read property 'length' of undefined" error you're hitting in your React pagination search component!

What's causing this?

The error points directly to movies.length in the line const maxPages = Math.floor(movies.length / PAGE_SIZE); — this means at the moment this code runs, movies is undefined. This usually happens in one of a few scenarios:

  • Your movies state isn't initialized with a default value (like an empty array)
  • The search function isn't correctly setting the movies state (e.g., API call fails, returns null, or data processing breaks)
  • You're trying to calculate maxPages before the search data has finished loading

Fixes you can try right away

1. Add a null/undefined check for movies

The quickest way to prevent the crash is to guard against movies being undefined when calculating maxPages:

// Option 1: Ternary check
const maxPages = movies ? Math.floor(movies.length / PAGE_SIZE) : 0;

// Option 2: Optional chaining + nullish coalescing (cleaner ES2020+)
const maxPages = Math.floor((movies?.length ?? 0) / PAGE_SIZE);

This ensures if movies is undefined, you'll default to a safe value (0) instead of throwing an error.

2. Initialize your movies state properly

Make sure when you set up your state for movies, you start with an empty array instead of undefined:

// Wrong: leaves movies as undefined initially
const [movies, setMovies] = useState();

// Right: initializes with an empty array so .length exists from the start
const [movies, setMovies] = useState([]);

3. Handle async search loading states

If movies comes from an API call when searching, add a loading state to avoid calculating maxPages before data arrives:

const [movies, setMovies] = useState([]);
const [loading, setLoading] = useState(false);

const handleSearch = async (searchQuery) => {
  setLoading(true);
  try {
    const response = await fetch(`/your-search-api?query=${searchQuery}`);
    const searchResults = await response.json();
    // Ensure we always set an array, even if results are empty
    setMovies(searchResults || []);
  } catch (error) {
    console.error("Search failed:", error);
    // Reset to empty array on error to avoid undefined
    setMovies([]);
  } finally {
    setLoading(false);
  }
};

Then in your component render, you can show a loading spinner instead of rendering pagination while data loads:

if (loading) {
  return <div>Loading results...</div>;
}

4. Debug to pinpoint the root cause

Add a quick console log right before calculating maxPages to see when movies becomes undefined:

console.log("Current movies value:", movies);
const maxPages = Math.floor(movies.length / PAGE_SIZE);

Check your browser's dev tools to see if this logs undefined on initial render, after a search, or in a specific edge case — this will help you narrow down exactly where the state is breaking.

内容的提问来源于stack exchange,提问作者user173420

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 10:12:44