React Principles Explained

React Principles Explained

1. setState() Description

1.1 Update data

setState() is used to update data asynchronously

You can call setState() multiple times, and it will only trigger a re-rendering once.

import React from 'react'
import ReactDOM from 'react-dom'
class Opp extends React.Component {
	state = {
		count: 1,
	}
	handleClick = () => {
		// Asynchronously update data this.setState({
			count: this.state.count + 1,
		})
        this.setState({
			count: this.state.count + 1,
		})
		console.log(this.state.count) // 1
	}
	render() {
		return (
			<div>
				<h1>Counter: {this.state.count}</h1>
				<button onClick={this.handleClick}>+1</button>
			</div>
		)
	}
}
ReactDOM.render(<Opp />, document.getElementById('root'))

1.2 Recommended syntax

Use the setState((state, props)=>{}) syntax

state: represents the latest state, props: represents the latest props

import React from 'react'
import ReactDOM from 'react-dom'
class Opp extends React.Component {
	state = {
		count: 1,
	}
	handleClick = () => {
		/* // Asynchronously update data this.setState({
			count: this.state.count + 1,
		})
		console.log(this.state.count) //1
    this.setState({
			count: this.state.count + 1,
		})
		console.log(this.state.count) //1
    */
		// Recommended syntax this.setState((state, props) => {
			return {
				count: state.count + 1,
			}
		})
		this.setState((state, props) => {
			console.log('Second call:', state) //2
			return {
				count: state.count + 1,
			}
		})
		console.log(this.state.count) // 3
	}
	render() {
		return (
			<div>
				<h1>Counter: {this.state.count}</h1>
				<button onClick={this.handleClick}>+1</button>
			</div>
		)
	}
}
ReactDOM.render(<Opp />, document.getElementById('root'))

1.3 Second Parameter

  • Perform an action immediately after the state is updated (the page has finished re-rendering)
  • Syntax: setState(updater[,callback])

callback refers to the callback function, which can be added or not

import React from 'react'
import ReactDOM from 'react-dom'
class Opp extends React.Component {
	state = {
		count: 1,
	}
	handleClick = () => {
		this.setState(
			(state, props) => {
				return {
					count: state.count + 1,
				}
			},
			// Execute immediately after the state is updated and re-rendered () => {
				console.log('Status update completed:', this.state.count) // 2
				console.log(document.getElementById('title').innerText) // Counter: 2
				document.title = 'Updated count is:' + this.state.count
			}
		)
		console.log(this.state.count) //1
	}
	render() {
		return (
			<div>
				<h1 id='title'>Counter: {this.state.count}</h1>
				<button onClick={this.handleClick}>+1</button>
			</div>
		)
	}
}
ReactDOM.render(<Opp />, document.getElementById('root'))

2. JSX syntax conversion process

  • JSX is just syntactic sugar (simplified syntax) for the createElement() method.
  • JSX syntax is compiled into createElement() method by @babel/preset-react plugin
  • React element: is an object that describes what you want to see on the screen

insert image description here

import React from 'react'
import ReactDOM from 'react-dom'
//Conversion process of JSX syntax// const element = <h1 className='greeting'>Hello JSX</h1>
const element = React.createElement(
	'h1',
	{
		className: 'greeting',
	},
	'Hello JSX'
)
console.log(element)
ReactDOM.render(element, document.getElementById('root'))

3. Component update mechanism

  • Two functions of setState(): 1. Modify state 2. Update components (UI)
  • Process: When the parent component is re-rendered, the child components will also be re-rendered, but only the current component subtree (the current component and all its child components) will be rendered

insert image description here

4. Component performance optimization

4.1 Reducing state

  • Reduce state: only store data related to component rendering (such as count/list data/loading, etc.)
  • Note: Do not put books that do not need to be rendered in the state (such as timer id, etc.)
  • Data that needs to be used in multiple methods should be placed in this

4.2 Avoid unnecessary re-rendering

  • Component update mechanism: Parent component updates will cause child components to be updated as well
  • Problem: Child components are re-rendered even when they have not changed, causing unnecessary re-rendering
  • Solution: Use the hook function shouldComponentUpdate(nextProps, nextState)
  • Function: Determines whether the component should be re-rendered by returning true, false means not to be re-rendered
  • Triggering time: Hook function in the update phase, executed before the component is re-rendered (shouldComponentUpdate -> render)
import React from 'react'
import ReactDOM from 'react-dom'
class Opp extends React.Component {
	state = {
		count: 0,
	}
	handleClick = () => {
		this.setState((state) => {
			return {
				count: this.state.count + 1,
			}
		})
	}
	//Hook function shouldComponentUpdate(nextProps, nextState) {
		// Return false to prevent the component from re-rendering // return false
		// The latest state console.log('latest state', nextState)
		// Status before update console.log(this.state)
		// Return true, the component re-renders return true
	}
	render() {
		console.log('Component updated')
		return (
			<div>
				<h1>Counter: {this.state.count}</h1>
				<button onClick={this.handleClick}>+1</button>
			</div>
		)
	}
}
ReactDOM.render(<Opp />, document.getElementById('root'))

Example: Random Numbers

Via nextState

import React from 'react'
import ReactDOM from 'react-dom'
// Generate random numbers class Opp extends React.Component {
	state = {
		number: 0,
	}
	handleClick = () => {
		this.setState((state) => {
			return {
				number: Math.floor(Math.random() * 3),
			}
		})
	}
	// The random numbers generated twice may be the same, so there is no need to re-render shouldComponentUpdate(nextState) {
		console.log('Latest state:', nextState, 'Current state:', this.state)
		return nextState.number !== this.state.number
		/* if ( nextState.number !== this.state.number) {
			return true
		}
		return false*/
	}
	render() {
		console.log('render')
		return (
			<div>
				<h1>Random number: {this.state.number}</h1>
				<button onClick={this.handleClick}>Regenerate</button>
			</div>
		)
	}
}
ReactDOM.render(<Opp />, document.getElementById('root'))

Via nextState

import React from 'react'
import ReactDOM from 'react-dom'
// Generate random numbers class Opp extends React.Component {
	state = {
		number: 0,
	}
	handleClick = () => {
		this.setState((state) => {
			return {
				number: Math.floor(Math.random() * 3),
			}
		})
	}
	render() {
		return (
			<div>
				<NumberBox number={this.state.number} />
				<button onClick={this.handleClick}>Regenerate</button>
			</div>
		)
	}
}
class NumberBox extends React.Component {
	shouldComponentUpdate(nextProps) {
		console.log('latest props:', nextProps, 'current props:', this.props)
		return nextProps.number !== this.props.number
	}
	render() {
		console.log('subcomponent render')
		return <h1>Random number: {this.props.number}</h1>
	}
}
ReactDOM.render(<Opp />, document.getElementById('root'))

Summarize

This article ends here. I hope it can be helpful to you. I also hope that you can pay more attention to more content on 123WORDPRESS.COM!

You may also be interested in:
  • A detailed explanation of how React Fiber works
  • ES6 class chain inheritance, instantiation and react super (props) principle detailed explanation
  • Detailed explanation of the usage and principle analysis of connect in react-redux
  • React-router 4 on-demand loading implementation and principle detailed explanation

<<:  Docker container monitoring principle and cAdvisor installation and usage instructions

>>:  Common symbols in Unicode

Recommend

How to export mysql query results to csv

To export MySQL query results to csv , you usuall...

A brief discussion on using virtual lists to optimize tables in el-table

Table of contents Preface Solution Specific imple...

Vue implements automatic jump to login page when token expires

The project was tested these days, and the tester...

Some suggestions for improving Nginx performance

If your web application runs on only one machine,...

Summary of methods to clear cache in Linux system

1) Introduction to cache mechanism In the Linux s...

JavaScript to implement the web version of Gobang game

This article shares the specific code for JavaScr...

Implementation of textarea adaptive height solution in Vue

Table of contents Hidden Problems Solution to ada...

Detailed tutorial for downloading and installing mysql8.0.21

Official website address: https://www.mysql.com/ ...

Ubuntu 16.04 image complete installation tutorial under VMware

This article shares with you the installation tut...

JS Easy to understand Function and Constructor

Table of contents 1. Overview 1.1 Creating a func...

Introduction to common MySQL storage engines and parameter setting and tuning

MyISAM, a commonly used storage engine in MySQL c...

Introduction to MyCat, the database middleware

1. Mycat application scenarios Mycat has been dev...