MENU
Setting and Using a State
This shows a ticking time.Notice how a state is initialized, set, and retrieved. When you call setState(), React merges the object you provide into the current state, allowing you to maintain the other state variables.<br>
<br>Like render(), constructor(), componentDidMount(), and componentWillUnmount() are special component lifecycle methods.
RESETRUNFULL
RESETRUNFULL
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()}; // may have more fields
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() { // this.state.date = new Date(); // changing a state directly won’t work
this.setState({date: new Date()});
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}}ReactDOM.render(
<Clock />,
document.getElementById('root'));