1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 07:08:01 +00:00

Add Defining State In A Simple Class Component as a react til

This commit is contained in:
jbranchaud
2018-02-04 12:43:34 -06:00
parent 13e8a7fa42
commit 352aa37f94
2 changed files with 52 additions and 1 deletions

View File

@@ -0,0 +1,50 @@
# Defining State In A Simple Class Component
Most class components start off with a constructor which does some
initialization of the component including setting the components initial
state. It might look something like the following:
```javascript
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: true
};
}
render() {
if (this.state.loading) {
return (
<p>Loading...</p>
);
} else {
// ...
}
}
}
```
If setting state is the only thing you need to do in the constructor,
then you can skip the constructor all together.
```javascript
class MyComponent extends React.Component {
state = {
loading: true
};
render() {
if (this.state.loading) {
return (
<p>Loading...</p>
);
} else {
// ...
}
}
}
```
This second example will work the same as the first, and it is a bit more
concise.