Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
In this video, we'll finish writing the handleScoreChange
function by updating state based on the index of a player object.
Video Update
While updating the score
state of a player, you may have noticed that prevState
references the same object as this.state
. For example, in React DevTools, you might see a new score
property added to the state
object when you update a player's score:
In the video, we used prevState
in this.setState()
to update a player's score based on the previous score. It turns out that prevState
is in fact still a reference to the previous state object, and it should not be directly mutated.
A better way to update a specific player's score might be as follows:
handleScoreChange = (index, delta) => {
this.setState( prevState => {
// New 'players' array – a copy of the previous `players` state
const updatedPlayers = [ ...prevState.players ];
// A copy of the player object we're targeting
const updatedPlayer = { ...updatedPlayers[index] };
// Update the target player's score
updatedPlayer.score += delta;
// Update the 'players' array with the target player's latest score
updatedPlayers[index] = updatedPlayer;
// Update the `players` state without mutating the original state
return {
players: updatedPlayers
};
});
}
This will build a new object based on the data from prevState
, which update a player's score
state without mutating this.state
:
This seems like the safest approach, especially when managing state across larger applications.
Kudos goes to students in this thread for pointing this out and making suggestions. The project files are also updated to reflect the change. :)
You need to sign up for Treehouse in order to download course files.
Sign up