Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Updating State2:14 with Guil Hernandez
In React, state is never modified directly. The only way React allows you to update a component's state is by using its built-in
Our increment button is now wired up to the incrementScore event handler. 0:00 So next, let's update the score state inside the incrementScore method. 0:05 Each time a user clicks the plus button, the counter score will increase by one. 0:10 It's important to remember that state is never modified directly. 0:16 In other words, we're not able to increment the score state by one, 0:21 like this. 0:25 The only way React allows you to update a component state is by using its 0:28 built-in set state method. 0:33 So inside incrementScore, let's call this.setState. 0:35 You see, React needs to be told when state changes. 0:41 So this.setstate lets React know that state has changed, and that it should 0:45 re-render and make changes to the component, based on the change in state. 0:50 You pass setState, an object that contains the part of the state you wanna update, 0:56 and the value you want to update it to. 1:01 In our case, we want to update the score state. 1:04 When incrementScore is called, 1:07 we want to set the score state to one more than its current value. 1:10 So for now, I'll set it to the current score plus one, 1:16 with this.state.score + 1. 1:21 So to recap, setState is going to do two things. 1:24 It will update the value of the score state, and 1:29 it will tell React that this component needs to be 1:33 re-rendered to make sure that everything is up to date in the UI. 1:36 Our method is all set to update the state, but 1:41 if we try to increment a player's score, nothing happens. 1:45 And we get an error in the console that says, 1:49 Uncaught TypeError: Cannot read property 'setState' of undefined. 1:52 It looks like we've lost our binding to the component, so 1:57 we're not able to reference it with this from within the incrementScore method. 2:01 It's common to experience this issue when handling events in React. 2:07 We'll look at why this happened and how to fix it in the next video 2:11
You need to sign up for Treehouse in order to download course files.Sign up