React State
State is similar to props, but it is private and fully controlled by the component.
class constructor
The constructor method is a special method for creating and initializing an object created with a class
. There can only be one special method with the name “constructor” in a class. A SyntaxError
will be thrown if the class contains more than one occurrence of a constructor
method.
Class components should always call the base constructor with props
.
constructor(props) {
super(props);
this.state = {date: new Date()};
}
Adding Lifecycle Methods to a Class
- componentDidMount(): The
componentDidMount()
method runs after the component output has been rendered to the DOM. - componentDidUnmount(): clear that timer whenever the DOM produced by the
Clock
is removed. This is called “unmounting” in React. ```javascript componentDidMount() { this.timerID = setInterval(
); }() => this.tick(),
1000
componentWillUnmount() { clearInterval(this.timerID); }
tick() { this.setState({ date: new Date() }); }
<a name="fRi5m"></a>
## Do Not Modify State Directly
```javascript
// Wrong
this.state.comment = 'Hello';
// Correct
this.setState({comment: 'Hello'});
State Updates May Be Asynchronous
React may batch multiple setState()
calls into a single update for performance.
Because this.props
and this.state
may be updated asynchronously, you should not rely on their values for calculating the next state.
// Wrong
this.setState({
counter: this.state.counter + this.props.increment,
});
// Correct
this.setState((state, props) => ({
counter: state.counter + props.increment
}));
The Data Flows Down
Neither parent nor child components can know if a certain component is stateful or stateless, and they shouldn’t care whether it is defined as a function or a class.
This is commonly called a “top-down” or “unidirectional” data flow. Any state is always owned by some specific component, and any data or UI derived from that state can only affect components “below” them in the tree.
function App() {
return (
<div>
<Clock />
<Clock />
<Clock />
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById('root')
);