React State


Release date:2024-03-12 Update date:2024-03-16 Editor:admin View counts:138

Label:

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:

  1. When <Clock /> be passed on to ReactDOM.render() react calls the Clock the constructor of the component. Due to Clock need to display the current time, so use an object that contains the current time toinitialize the this.state . We will update this status later.

  2. React then calls Clock component render() method. This is React knowing what should be displayed on the screen, and then React updates DOM to match Clock the rendered output of the.

  3. When Clock the output of the is inserted into the DOM, React calls componentDidMount() life cycle hooks. In which Clock component requires the browser to set a timer that is called once per second tick() .

  4. The browser calls every second tick() method. In which Clock Ccomponent is called by using an object containing the current time setState() to schedule UI updates. By calling the setState() react knows that the state has changed and calls the render() method to determine what should be displayed on the screen. This time, render() In the method this.state.date will be different, so the rendered outputwill contain the update time and update the DOM accordingly.

  5. Once Clock the component is removed from the DOM and React calls the componentWillUnmount() . 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.

Powered by TorCMS (https://github.com/bukun/TorCMS).