Function encapsulates the clock component
The Clock component requires a timer to update every second
function Clock(props) {
return (
<h2>{props.date.toLocaleTimeString()}</h2>)}function tick() {
ReactDOM.render(
<Clock date={new Date()} / >.document.getElementById('root'); }setInterval(tick, 1000);
Copy the code
We want the Clock component to update itself, so we use the state property. State is similar to props, but state is private and completely controlled by the current component.
Replace the function component with a class component
1. Create an ES6 class that inherits from react.component. then put the function body in an empty render() method, and make sure that the render() method replaces the props with this.props as follows:
class Clock extends React.Component {
render() {
return (
<h2>{this.props.date.toLocaleTimeString()}</h2>)}}Copy the code
Add a class constructor to the function, initialize this.state, pass props to the parent constructor as super, and then replace this.props. Date with this.state.date in the render() method as follows:
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date:new Date(a)}; }render(){
return (
<h2>{this.state.date.toLocaleTimeString()}</h2>
)
}
}
ReactDOM.render(
<Clock />.// Remove the date attribute
doncument.getElementById('root'));Copy the code
Add the lifecycle method to the Class function to implement the timer:
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date:new Date(a)}; }componentDidMount() { // Mount function
this.timerID = setInterval(
() = > this.tick(),
1000
);
// save the timerID in this.timerid
}
componentWillUnmount() { // Unload the function
clearInterval(this.timerID);
}
tick() { // Timer method
this.setState({ // Update component state at any time
date: new Date()}); }render() {
return (
<h2>{this.state.date.toLocaleTimeString()}</h2>
)
}
}
ReactDOM.render(
<Clock />.document.getElementById('root'); ;Copy the code
~ Use state correctly
The constructor is the only place you can assign a value to this.state. Do not modify state directly, this.state.date = ‘.. ‘does not render components, only this.setState({date:’.. ‘}) will render the component
For performance reasons, React might combine multiple setState() calls into a single call, forming an asynchronous update
// This line of code may not be updated
this.setState({
counter:this.state.counter + this.props.increment
})
// The solution to this problem is to accept a function in the setState() method that uses a state as the first argument and props as the second
this.setState((state, props) = > ({
counter: state.counter + props.increment
}))
Copy the code