调用GitHub API获取用户数据时出现undefined属性读取错误求助
First, let's look at the error you're encountering:
Let's break down the issues and fixes step by step:
1. Critical: Missing Return in Loading State (Results.js)
This is almost certainly the immediate cause of your error. In your Results component's render method, when loading is true, you render a loading message but don't return it. That means the code keeps running and tries to render the Player components even while your app is still fetching data.
Since your initial state sets winner and loser to empty objects ({}), accessing winner.score or winner.profile will return undefined. When the Player component passes this undefined value as the profile prop to Profile, trying to read info.avatar_url throws the "Cannot read property of undefined" error you see.
Fix: Add a return statement to the loading check:
if(loading === true){ return <p> Loading !! </p> }
2. Incomplete PlayerPreview Component
Your PlayerPreview.js code is truncated halfway through defining propTypes, which creates a syntax error that will break the component:
PlayerPreview.propTypes = { av
Fix: Complete the propTypes definition to validate required props properly:
PlayerPreview.propTypes = { avatar: PropTypes.string.isRequired, username: PropTypes.string.isRequired };
3. Safeguard Against Null Player Data
In your API call, if getUserData returns null (via the handleError function), your players array could contain null values. Setting winner or loser to null will cause errors when accessing their properties later.
Fix: Add a check to handle null entries in the players array:
api.battle([ players.playerOneName, players.playerTwoName ]).then(function (players){ if (players === null || players.some(player => player === null)) { return this.setState(function () { return { error: 'Looks like there was an error. Check that both users exist on Github.', loading: false, } }); } this.setState(function () { return { error: null, winner: players[0], loser: players[1], loading: false, } }); }.bind(this));
Bonus: Add Defensive Checks
To prevent similar issues in the future, use optional chaining (?.) in your Profile component to safely access properties that might be missing from API responses:
<PlayerPreview avatar={info?.avatar_url} username={info?.login}> <ul className='space-list-items'> {info?.name && <li>{info.name}</li>} {info?.location && <li>{info.location}</li>} <li>Followers: {info?.followers || 0}</li> <li>Following: {info?.following || 0}</li> <li>Public Repos: {info?.public_repos || 0}</li> {info?.blog && <li><a href={info.blog}>{info.blog}</a></li>} </ul> </PlayerPreview>
Start with fixing the loading state return—this should resolve your immediate error. Then address the other issues to make your code more robust!
内容的提问来源于stack exchange,提问作者Riya

