调用GitHub外部API更新React组件状态时出现null属性读取错误
Hey there! Let's dig into that "Cannot read properties of null (reading 'score')" error you're hitting. After looking over your code and error details, the root issue is in your Results component's render method—you’re trying to access properties like winner.score when winner or loser might still be null (either while loading or when an API error occurs).
Here’s how to fix it step by step:
1. Add return to your loading state check
Right now, when loading is true, you render a loading message but don’t return it. That means the rest of the render code still runs, trying to access winner.score even though winner is still null. Adding a return here stops the component from executing further logic until loading is complete.
2. Restructure render logic with early returns
Handle loading and error states first, returning early before trying to render the player components. This ensures you never attempt to access properties on null values.
3. Add a safety check for valid player data
Even if the API call succeeds, it’s a good idea to verify winner and loser exist before rendering the Player components to avoid unexpected edge cases.
Here’s the updated render method for your Results component:
render () { const { error, winner, loser, loading } = this.state; // Early return for loading state if (loading) { return <p>Loading !!</p>; } // Early return for error state if (error) { return ( <div> <p>{error}</p> <Link to='/battle'>Reset</Link> </div> ); } // Safety check to ensure player data exists if (!winner || !loser) { return ( <div> <p>Something went wrong retrieving player data.</p> <Link to='/battle'>Reset</Link> </div> ); } // Render players only when all data is ready return ( <div className='row'> <Player label='Winner' score={winner.score} profile={winner.profile} /> <Player label='Loser' score={loser.score} profile={loser.profile} /> </div> ) }
A quick side note: Your Player component’s propTypes require a profile prop, but the component doesn’t actually use it. You can either remove that prop from the propTypes or update the Player component to display profile data (like the user’s avatar or username) to make use of it.
内容的提问来源于stack exchange,提问作者Riya

