ReactJS调用API报错:Cannot read property 'title' of undefined 求助
Hey there! That error is super common when working with APIs in React—let’s break down what’s happening and how to fix it.
What’s Causing This?
The error means you’re trying to access the title property on a variable that’s undefined at the time the component renders. Since you’re fetching data from a movie API, this almost always happens because:
- The API data hasn’t loaded yet when the component first renders, or
- The API call failed, so your movie state never got populated, or
- The structure of the API response isn’t what you expected (so the path to
titleis wrong).
Fix 1: Add Loading/Error States & Conditional Rendering
React renders your component before the API call finishes, so your movie state is probably undefined initially. You need to handle that case.
First, initialize your state properly (use null instead of leaving it undefined):
const [movie, setMovie] = useState(null);
Then, in your JSX, check if movie exists before trying to access title:
{movie ? <h1>{movie.title}</h1> : <p>Loading movie...</p>}
Or use optional chaining for a shorter, safer syntax:
<h1>{movie?.title}</h1>
This will skip accessing title if movie is null or undefined.
Fix 2: Handle API Errors
If your API call fails (network issue, invalid key, etc.), your movie state will stay undefined. Add a try/catch block around your fetch to handle errors gracefully:
const fetchRandomMovie = async () => { try { const response = await fetch('your-movie-api-url'); if (!response.ok) throw new Error('API request failed'); const data = await response.json(); // Make sure you're picking a valid item from the response array const randomMovie = data.results[Math.floor(Math.random() * data.results.length)]; setMovie(randomMovie); } catch (error) { console.error('Error fetching movie:', error); // Optionally set an error state to show to the user setError('Failed to load movie. Please try again.'); } };
Fix 3: Verify the API Response Structure
Sometimes the issue is that the API returns data in a different format than you expect. Add a console.log right after parsing the JSON to inspect the response:
const data = await response.json(); console.log('API Response:', data);
Check if the title is actually under title, or if it’s nested somewhere else (like data.movie.title or data.items[0].title). Also, ensure the array you’re picking a random item from exists and isn’t empty before accessing an index.
Quick Debugging Tip
Use React DevTools to inspect your component’s state and see if movie is being set correctly. If it’s still undefined after the API call, the problem is in how you’re fetching or processing the data.
Hope these steps help you fix the issue—good luck with your internship project!
内容的提问来源于stack exchange,提问作者Kieran Burford

