React State state and life cycle implementation method

React State state and life cycle implementation method

1. Methods for implementing components:

組件名稱首字母必須大寫

1. Implement components through JS functions

<div id="app"></div>
<script type="text/babel">
  var ReactDiv = document.getElementById('app');
  function GetReactComp(){
    return <p>I am a react component</p>
  }
  const hellocomp = < GetReactComp /> //Capitalize the first letter const reactSpan = (
    <span>
      { hellocomp }
    </span>
  )
  ReactDOM.render(reactSpan, ReactDiv)
</script>

2. Implement components through ES6 class

<div id="class"></div>
<script type="text/babel">
  var reactDiv1=document.getElementById('class');
  //Define class component class MyReactComp extends React.Component{
    render(){
      return (
        <h2>Class Components</h2>
      )
    }
  }
  //Use class component const testDiv = (
    <div>{<MyReactComp/>}</div>
  )
	//Mount ReactDOM.render(testDiv,reactDiv1)
</script>

2. Props component value transfer

React has a strict protection mechanism for props. Once a value is given,不允許被改變in the component.

<div id="app"></div>
<script type="text/babel">
  var reactDiv = document.getElementById('app');
  class ReactClassComp extends React.Component {
    render(){
      return (
      <div>
      <p>Username: <input type="text" value={ this.props.name }/></p>
      <p>Gender: <input type="text" value={ this.props.gender }/></p>
      </div>
      )
    }
  }

  ReactClassComp.defaultProps={
    name:'Liu Bei',
    gender:'male'
  }
  const reactp = (
    <span>
      {<ReactClassComp />}  
    </span>
  )
  ReactDOM.render(reactdiv,reactdiv)
</script> 

insert image description here

Note: In many cases, the content of the component needs to be refreshed according to the refresh of the data. At this time, you need to use the State provided by React.

3. State

  • React regards components as狀態機, interacts with users through internally defined states and life cycles, maintains different states of components, and then ensures user interface and data consistency by rendering UI.
  • Creation method: Using the ES6 class inheritance method super , props can be passed to the React.Component constructor.

1. React life cycle mounting (mount):

When a component instance is created and inserted into the DOM

(1) constructor(props) --> Before the component is mounted, its constructor will be called. If you do not need to initialize state or bind methods, you do not need to create a constructor.

Constructors are only used in the following two cases:

  • Initialize the internal state by assigning an object to this.state
  • Bind an instance to an event handler

Note: Do not call the setState() method in the constructor() function. If you need to use internal state, you can directly assign this.state to initialize state in the constructor.

constructor(props){
	super(props);
		this.state = {
			date:new Date()
		}
		this.handleShow = this.handleShow.bind(this)
	
}

(2) render() --> must be implemented

It checks this.props and this.state for changes and returns one of the following types:

  • React elements: usually created with JSX
  • Array or fragments: returns multiple
  • Portals: can render nodes into different DOM subtrees
  • String or numeric type: rendered as a text node
  • Boolean or null: render nothing

純函數: It returns the same result every time it is called without modifying the component state, and it does not interact directly with the browser.
If you need to interact with the browser, define it in ComponentDidMount() or other life cycle

(3) ComponmentDidMount() -->Called immediately after the component is mounted.

  • Depends on the initialization of DOM nodes
  • Instantiate network request to obtain data
  • Add a subscription and unsubscribe in componentWillUnmount()

Note: You can call setState() directly in ComponentDidMount(). It will trigger an additional render, but this render will happen before the browser updates the screen. This ensures that even if render() is called twice, the user will not see the intermediate state.

renew:

compomentDidUpdate(prevProps,prevProps,snapshot) : Called immediately after the update. This method will not be executed for the first rendering. When the component is updated, the DOM can be operated here.

compomentDidUpdate(prevProps){
	if(this.props.userID !== prevProps.userID){
		this.fetchData(this.props.userID)
	}
}

Note: If you call setState() in compositionDidUpdate(), you need to wrap it in a conditional statement, otherwise it will cause an infinite loop. It will also cause an extra re-render, which, while invisible to the user, will affect component performance.

uninstall:

componentWillUnmount() -->Called directly before a component is uninstalled and destroyed.
Note: setState() should not be called in componentWillUnmount() because the component will never re-render. Once a component instance is unmounted, it will never be mounted again.

2. Lifecycle instance-->Clock:

<div id="app"></div>
<script type="text/babel">
  var reactDiv = document.getElementById('app')
  //Define the class component MyStateComp 
  class MyStateComp extends React.Component {
    //Constructor constructor(props) {
      super(props); 
      // Initialize state internally through this.state this.state = {
        date:new Date(),
        show:false,
        text:'display'
      }
      //Bind an instance to the event handling function this.handleShow = this.handleShow.bind(this)
    }
    //Add subscription componentDidMount() {
      this.timerID = setInterval(()=>this.tick(),1000)
    }
    //Time function tick() {
      this.setState({ //setState updates the state of the component
        date:new Date()
      })
    }
    //Instance display, hide handleShow() {
      this.setState(state=>({
        show: !state.show,
        text: !state.show?'Hide':'Show'
      }))
    }
    //Component uninstallation: clear the timer componentWillUnmont() {
      clearInterval(this.timerID)
    }
    
    render() {
      let isShow = this.state.show;
      let element;
      if(isShow){
        element = <h2 >{this.state.date.toLocaleTimeString()}</h2> 
      }else{
        element = null
      }
      return (
        <div>
          <button onClick={this.handleShow}>{this.state.text}time</button>
          {element}
        </div>
      )
    }
  }
  const reactSpan = (
    <span>
      {<MyStateComp/> }  
    </span>
  )
  ReactDOM.render(reactSpan, reactDiv)
</script> 

insert image description here

This is the end of this article about React State and life cycle. For more relevant React State life cycle content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of the abbreviation of state in react
  • Detailed explanation of the use of state in React's three major attributes
  • A brief discussion on React's state
  • A brief analysis of React's understanding of state

<<:  How to use Nexus to add jar packages to private servers

>>:  How to install and modify the initial password of mysql5.7.18

Recommend

MySQL data operation-use of DML statements

illustrate DML (Data Manipulation Language) refer...

Mysql: The user specified as a definer ('xxx@'%') does not exist solution

During the project optimization today, MySQL had ...

Linux service monitoring and operation and maintenance

Table of contents 1. Install the psutil package S...

JavaScript imitates Xiaomi carousel effect

This article is a self-written imitation of the X...

How to set up the terminal to run applications after Ubuntu starts

1. Enter start in the menu bar and click startup ...

How to implement html input drop-down menu

Copy code The code is as follows: <html> &l...

Exploration of three underlying mechanisms of React global state management

Table of contents Preface props context state Sum...

IDEA configuration process of Docker

IDEA is the most commonly used development tool f...

About Vue virtual dom problem

Table of contents 1. What is virtual dom? 2. Why ...

Vue uses v-model to encapsulate the entire process of el-pagination components

Use v-model to bind the paging information object...

Solution to the failure of docker windows10 shared directory mounting

cause When executing the docker script, an error ...