React State
React treats components as a state machine (State Machines). Achieve different states by interacting with the user, and then render the UI to keep the user interface and data consistent.
In React, you only need to update the state
and then according to the new state
re-render the user interface (do not manipulate DOM).
The following example creates a name that extends to React.Component
. The ES6 class of the render()
method used in the this.state
to modify the current time.
Add a class constructor to initialize the state this.state
class components should always use the props
call the underlying constructor.
React instance
classClockextendsReact.Component{constructor(props){super(props);this.state={date:newDate()};}render(){return(<div>
<h1>Hello,world!</h1>
<h2>Now it's {this.state.date.toLocaleTimeString()}.</h2>
</div>);}}ReactDOM.render(<Clock/>,document.getElementById('example'));
Next, we will have Clock set its own timer and update it every second.
Add a lifecycle method to a class
In applications with many components, it is important to release the resources consumed by the components at the time of destruction.
Whenever Clock
component is loaded into the DOM
we all want to generate a timer, which is in the React
is called mounting.
Similarly, whenever Clock
generated this. DOM
when it is removed, we also want to clear the timer, which is in the React
is called uninstalling.
We can declare special methods on the component class to run some code when the component is mounted or unloaded:
React instance
classClockextendsReact.Component{constructor(props){super(props);this.state={date:newDate()};}componentDidMount(){this.timerID=setInterval(()=>this.tick(),1000);}componentWillUnmount(){clearInterval(this.timerID);}tick(){this.setState({date:newDate()});}render(){return(<div>
<h1>Hello,world!</h1>
<h2>Now it's{this.state.date.toLocaleTimeString()}.</h2>
</div>);}}ReactDOM.render(<Clock/>,document.getElementById('example'));
Instance resolution:
componentDidMount()
and componentWillUnmount()
methods are called lifecycle hooks.
Executes after the component is output to DOM componentDidMount()
, Hook,we can set a timer on this hook.
this.timerID
for the ID of the timer, we can use the componentWillUnmount()
uninstall the timer in the hook.
Code execution order:
When
<Clock />
be passed on toReactDOM.render()
react calls theClock
the constructor of the component. Due toClock
need to display the current time, so use an object that contains the current time toinitialize thethis.state
. We will update this status later.React then calls
Clock
componentrender()
method. This is React knowing what should be displayed on the screen, and then React updates DOM to matchClock
the rendered output of the.When
Clock
the output of the is inserted into the DOM, React callscomponentDidMount()
life cycle hooks. In whichClock
component requires the browser to set a timer that is called once per secondtick()
.The browser calls every second
tick()
method. In whichClock
Ccomponent is called by using an object containing the current timesetState()
to schedule UI updates. By calling thesetState()
react knows that the state has changed and calls therender()
method to determine what should be displayed on the screen. This time,render()
In the methodthis.state.date
will be different, so the rendered outputwill contain the update time and update the DOM accordingly.Once
Clock
the component is removed from the DOM and React calls thecomponentWillUnmount()
. This hook function, the timer will also be cleared.
Data flows from top to bottom
Neither the parent component nor the child component can know whether a component is stateful or stateless, and they should not care whether a component is defined as a function or a class.
This is why the state is often referred to as local or encapsulation. Exceptfor the component that owns and sets it, other components are not accessible.
In the following example FormattedDate
the component will receive the date
value, and do not know that it comes from Clock
status, or from Clock
or enter it manually:
React instance
functionFormattedDate(props){return<h2>Now it's{props.date.toLocaleTimeString()}.</h2>;}classClockextendsReact.Component{constructor(props){super(props);this.state={date:newDate()};}componentDidMount(){this.timerID=setInterval(()=>this.tick(),1000);}componentWillUnmount(){clearInterval(this.timerID);}tick(){this.setState({date:newDate()});}render(){return(<div>
<h1>Hello,world!</h1> <FormattedDatedate={this.state.date}/>
</div>);}}ReactDOM.render(<Clock/>,document.getElementById('example'));
This is often referred to as top-down or unidirectional data flow. Any stateis always owned by certain components, and any data or UI exported from that state can only affect components below the tree.
If you imagine a component tree as a waterfall of attributes, the state of each component is like an additional water source, which is connected at anypoint, but also flows down.
To show that all components are truly isolated, we can create an App component that renders three Clock
:
React instance
functionFormattedDate(props){return<h2>Now it's{props.date.toLocaleTimeString()}.</h2>;}classClockextendsReact.Component{constructor(props){super(props);this.state={date:newDate()};}componentDidMount(){this.timerID=setInterval(()=>this.tick(),1000);}componentWillUnmount(){clearInterval(this.timerID);}tick(){this.setState({date:newDate()});}render(){return(<div>
<h1>Hello,world!</h1> <FormattedDatedate={this.state.date}/>
</div>);}}functionApp(){return(<div> <Clock/> <Clock/> <Clock/>
</div>);}ReactDOM.render(<App/>,document.getElementById('example'));
Each of the above examples Clock
components set up their own timers and update them independently.
In React
an application, whether a component is stateful or stateless is considered to be the implementation details of a component that may change over time.
We can use stateless components in stateful components, or we can use stateful components in stateless components.