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

A brief discussion on the synchronization solution between MySQL and redis cache

Table of contents 1. Solution 1 (UDF) Demo Case 2...

foreman ubuntu16 quick installation

Quickstart Guide The Foreman installer is a colle...

What can I use to save you, my table (Haiyu Blog)

Tables once played a very important role in web p...

HTML tutorial, understanding the optgroup element

Select the category selection. After testing, IE ...

How to display a small icon in front of the browser URL

When you browse many websites, you will find that ...

Install OpenSSL on Windows and use OpenSSL to generate public and private keys

1. OpenSSL official website Official download add...

Causes and solutions to the garbled character set problem in MySQL database

Preface Sometimes when we view database data, we ...

Summary of the use of element's form elements

There are many form elements. Here is a brief sum...

JS implementation of carousel example

This article shares the specific code of JS to im...

How to create a MySQL database (de1) using commands

1. Connect to MYSQL Format: mysql -h host address...

MySQL isolation level detailed explanation and examples

Table of contents 4 isolation levels of MySQL Cre...

React Routing Link Configuration Details

1. Link's to attribute (1) Place the routing ...

CSS implements six adaptive two-column layout methods

HTML structure <body> <div class="w...

jQuery implements form validation

Use jQuery to implement form validation, for your...