change setState to use a function

Also added note to readme
This commit is contained in:
Matt Pham
2019-02-27 02:37:14 -08:00
parent 119fb5785d
commit 96412d1d97
2 changed files with 6 additions and 4 deletions

View File

@@ -168,7 +168,7 @@ Our next step is to wire up the button to increment the `counter` in our compone
```jsx
_onButtonCLick = () => {
this.setState({ counter: this.state.counter + 1 });
this.setState(prevState => ({ counter: prevState.counter + 1 }));
};
```
@@ -176,6 +176,8 @@ This function will update our component state, incrementing our counter value by
> Note that this isn't exactly a method, but a property that is equal to a [arrow function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions). This works just as well as `onButtonClick() { }`, but doesn't require extra binding up in the constructor.
> Also note that `setState()` may update the state [asynchronously](https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous). If the next state depends on the previous state or props, then we should use the second form of `setState()` which takes a function that receives the previous state as the first argument and the props as the second.
Now that we have a function to increment out count, all that we have left is to connect it to our button.
```jsx

View File

@@ -14,12 +14,12 @@ export class Counter extends React.Component<any, any> {
return (
<div>
{text}: {counter}
<Button onClick={this._onButtonCLick}>Click</Button>
<Button onClick={this._onButtonClick}>Click</Button>
</div>
);
}
_onButtonCLick = () => {
this.setState({ counter: this.state.counter + 1 });
_onButtonClick = () => {
this.setState((state) => ({ counter: state.counter + 1 }));
};
}