mirror of
https://github.com/microsoft/frontend-bootcamp.git
synced 2026-01-26 14:56:42 +08:00
Merge pull request #22 from mattpham/change-1
change setState to use a function
This commit is contained in:
@@ -170,7 +170,7 @@ Our next step is to wire up the button to increment the `counter` in our compone
|
|||||||
|
|
||||||
```jsx
|
```jsx
|
||||||
_onButtonCLick = () => {
|
_onButtonCLick = () => {
|
||||||
this.setState({ counter: this.state.counter + 1 });
|
this.setState(prevState => ({ counter: prevState.counter + 1 }));
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -178,6 +178,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.
|
> 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.
|
Now that we have a function to increment out count, all that we have left is to connect it to our button.
|
||||||
|
|
||||||
```jsx
|
```jsx
|
||||||
|
|||||||
@@ -14,12 +14,12 @@ export class Counter extends React.Component<any, any> {
|
|||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
{text}: {counter}
|
{text}: {counter}
|
||||||
<Button onClick={this._onButtonCLick}>Click</Button>
|
<Button onClick={this._onButtonClick}>Click</Button>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
_onButtonCLick = () => {
|
_onButtonClick = () => {
|
||||||
this.setState({ counter: this.state.counter + 1 });
|
this.setState((state) => ({ counter: state.counter + 1 }));
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user