current position:Home>Summary of react learning (2)

Summary of react learning (2)

2022-01-26 23:53:00 APythonC

be-all Tips All of them are me OneNote Notes in , The copy is the picture , Too lazy to turn the text

Chapter two :React Component-oriented programming

One 、 Basic understanding and use

1.1 Use React Developer tools debugging

 Insert picture description here

1.2 Functional component

//1. Create functional components 
function MyComponent(){
    
	console.log(this); // Here this yes undefined, because babel Strict mode is turned on after compilation 
	return <h2> I'm a component defined by a function ( Apply to 【 Simple components 】 The definition of )</h2>
}
//2. Render component to page 
ReactDOM.render(<MyComponent/>,document.getElementById('test'))

Yes ReactDOM.render() after , What happened? ?

  1. React Parsing component Tags , eureka MyComponent Components
  2. Discover that components are defined using functions , The function is then called. , The virtual machine that will be returned DOM Turn to reality DOM, Then it appears on the page

1.3 Class components

//1. Create a class component 
class MyComponent extends React.Component {
    
	render(){
    
		//  Methods defined in class , They are all placed on the prototype object of the class , For instance 
		//render Where did you put it ?—— MyComponent On the prototype object , For example .
		//render Medium this Who is it? ?—— MyComponent Instance object of  <=> MyComponent Component instance object .
		console.log('render Medium this:',this);
		return <h2> I'm a component defined by a class ( Apply to 【 Complex components 】 The definition of )</h2>
	}
}
//2. Render component to page 
ReactDOM.render(<MyComponent/>,document.getElementById('test'))

Yes ReactDOM.render() after , What happened? ?

  1. React Parsing component Tags , eureka MyComponent Components
  2. Discovery components are defined using classes , And then new Come up with an instance of this class , And call the render Method
  3. take render Back to the virtual DOM Turn to reality DOM, Then it appears on the page

1.4 Pay attention to the point

  1. Component names must be capitalized
  2. fictitious DOM Element can only have one root element
  3. fictitious DOM Element must have an end tag
  4. Methods defined in class , They are all placed on the prototype object of the class , For instance
  5. By default, methods in the class turn on local strict mode , therefore this Pointing to undefined

1.5 The basic process of rendering class component labels

  1. React Internally, component instance objects are created
  2. call render() Get virtual DOM , And it's true DOM
  3. Insert inside the specified page element

Two 、 Three core attributes of component instances 1 —— state

2.1 for instance

//1. Create components 
class Weather extends React.Component{
    
	// Initialization status 
	state = {
    isHot:false,wind:' breeze '}

	render(){
    
		//  Deconstruct assignment to get  state
		const {
    isHot,wind} = this.state
		return <h1 onClick={
    this.changeWeather}> It's very... Today {
    isHot ? ' scorching hot ' : ' cool '},{
    wind}</h1>
	}

	// Custom method ———— In the form of an assignment statement + Arrow function 
	changeWeather = () => {
    
		const isHot = this.state.isHot
		this.setState({
    isHot:!isHot})
	}
}
//2. Render component to page 
ReactDOM.render(<Weather/>,document.getElementById('test'))

2.2 understand state

  1. state Is the most important property of a component object , Value is the object ( It can contain more than one key-value The combination of )
  2. Components are called " State machine ", You can't modify or update state To update the corresponding page display ( Rerender component )

2.3 Pay close attention to

  1. In the component render Methods this You can't modify or update
  2. You can't modify or update this by undefined, How to solve ?
    (1) Force binding this: You can't modify or update bind()
    (2) Arrow function ( In the arrow function this Point to the outer layer , Point here to Weather)
  3. Status data , You can't modify or update
  4. Pay serious attention to : The state must pass through setState updated , And update is a kind of merge , It's not a replacement
  5. This is the wrong way to write :this.state.isHot = !isHot

3、 ... and 、 Three core attributes of component instances 2 —— props

Functional components don't have state and resf attribute , Only props

3.1 for instance

// Create components 
class Person extends React.Component{
    
	constructor(props){
    
		// Whether the constructor receives props, Whether to pass to super, Depending on : Whether you want to pass... In the constructor this visit props
		// General constructors can omit 
		super(props)
		console.log('constructor',this.props);
	}

	// Type tag properties 、 The limits of necessity 
	static propTypes = {
    
		name:PropTypes.string.isRequired, // Limit name Will pass , And is a string 
		sex:PropTypes.string,// Limit sex For the string 
		age:PropTypes.number,// Limit age Is the value 
	}

	// Specifies the default label attribute value 
	static defaultProps = {
    
		sex:' male ',//sex The default value is male 
		age:18 //age The default value is 18
	}
			
	render(){
    
		const {
    name,age,sex} = this.props
		//props Is read-only 
		//this.props.name = 'jack' // This line of code will report an error , because props Is read-only 
		return (
			<ul>
				<li> full name :{
    name}</li>
				<li> Gender :{
    sex}</li>
				<li> Age :{
    age+1}</li>
			</ul>
		)
	}
}
// Render component to page 
ReactDOM.render(<Person name="jerry"/>,document.getElementById('test1'))
// {...p} For batch delivery props, Also known as batch transfer tag attribute , The expansion operator cannot expand an object , But introduce react file , Write babel Code , You can use the expand operator to expand 
// const p = {name:' Lao Liu ',age:18,sex:' Woman '}
// ReactDOM.render(<Person {...p}/>,document.getElementById('test3'))

3.2 understand props

  1. Every component object will have props(properties Abbreviation ) attribute
  2. All properties of the component tag are stored in props in

3.3 effect

  1. Pass the changed data from the outside to the inside of the component through the tag attribute
  2. Be careful : Do not modify inside the component props data

3.4 Function components use props

// Create components 
function Person (props){
    
	const {
    name,age,sex} = props
	return (
			<ul>
				<li> full name :{
    name}</li>
				<li> Gender :{
    sex}</li>
				<li> Age :{
    age}</li>
			</ul>
	)
}
Person.propTypes = {
    
	name:PropTypes.string.isRequired, // Limit name Will pass , And is a string 
	sex:PropTypes.string,// Limit sex For the string 
	age:PropTypes.number,// Limit age Is the value 
}
// Specifies the default label attribute value 
Person.defaultProps = {
    
	sex:' male ',//sex The default value is male 
	age:18 //age The default value is 18
}
// Render component to page 
ReactDOM.render(<Person name="jerry"/>,document.getElementById('test1'))

Four 、 Three core attributes of component instances 3 —— refs

4.1 for instance

// Create components 
class Demo extends React.Component{
    
	// Display the data in the left input box 
	// In string form ref
	showData = ()=>{
    
		const {
    input1} = this.refs
		alert(input1.value)
	}
	// Display the data in the input box on the right 
	// In the form of callbacks ref
	showData2 = ()=>{
    
		const {
    input2} = this
		alert(input2.value)
	}
	render(){
    
		return(
			<div>
				<input ref="input1" type="text" placeholder=" Click the button to prompt data "/>&nbsp;
				<button onClick={
    this.showData}> Click the data on the left of my prompt </button>&nbsp;
				<input ref={
    c => this.input2 = c } onBlur={
    this.showData2} type="text" placeholder=" Lost focus prompt data "/>
			</div>
		)
	}
}
// Render component to page 
ReactDOM.render(<Demo/>,document.getElementById('test'))

4.2 understand refs

Tags within components can define ref Attribute to identify yourself

4.3 code

  1. In string form ref
<input ref="input1"/>
  1. In the form of callbacks ref
//  Place the current node on the component instance itself , And named him  input1
// c  yes  currentNode  It means 
<input ref = c => this.input1 = c />
  1. createRef establish ref Containers
// React.createRef After calling, you can return a container , The container can be used to store ref The identified node , The container is “ Specially assigned person ” Of 
class Demo extends React.Component{
    
	// With a few, you have to create a few 
	myRef = React.createRef()
	myRef2 = React.createRef()
	// Display the data in the left input box 
	showData = ()=>{
    
		// current  It's inside the container  key
		alert(this.myRef.current.value);
	}
	// Display the data in the input box on the right 
	showData2 = ()=>{
    
		alert(this.myRef2.current.value);
	}
	render(){
    
		return(
			<div>
				<input ref={
    this.myRef} type="text" placeholder=" Click the button to prompt data "/>&nbsp;
				<button onClick={
    this.showData}> Click the data on the left of my prompt </button>&nbsp;
				<input onBlur={
    this.showData2} ref={
    this.myRef2} type="text" placeholder=" Lost focus prompt data "/>&nbsp;
			</div>
		)
	}
}
// Render component to page 
ReactDOM.render(<Demo/>,document.getElementById('test'))

4.4 Pay attention to the point

  1. The callback function in the form of inline is no different from that in the form of class binding , Inline will be called more than once when updating , It can be used directly
  2. In string form ref The efficiency is not high
  3. createRef Creating containers is cumbersome , With one, you have to create one , So use less

5、 ... and 、 Event handling

  1. adopt onXxx Property to specify the event handler ( Pay attention to case )
    (1)React Using custom ( synthesis ) event , Instead of using native DOM event —————— For better compatibility
    (2)React Events in are handled through event delegation ( Delegate to the outermost element of a component ) ———————— For efficiency
  2. adopt event.target Get information about what happened DOM Element object —————————— Don't overuse ref
showData2 = (event)=>{
    
	alert(event.target.value);
}

6、 ... and 、 Collect form data

6.1 Controlled components

characteristic : Save the input into the status (state), Take it again when you need it ( It can be omitted ref)

// Create components 
class Login extends React.Component{
    
	// Initialization status 
	state = {
    
		username:'', // user name 
		password:'' // password 
	}
	// Save user name to status 
	saveUsername = (event)=>{
    
		this.setState({
    username:event.target.value})
	}
	// Save password to status 
	savePassword = (event)=>{
    
		this.setState({
    password:event.target.value})
	}
	// Callback for form submission 
	handleSubmit = (event)=>{
    
		event.preventDefault() // Block form submission 
		const {
    username,password} = this.state
		alert(` The user name you entered is :${
      username}, The password you entered is :${
      password}`)
	}
	render(){
    
		return(
			<form onSubmit={
    this.handleSubmit}>
				 user name :<input onChange={
    this.saveUsername} type="text" name="username"/>
				 password :<input onChange={
    this.savePassword} type="password" name="password"/>
				<button> Sign in </button>
			</form>
		)
	}
}
// Rendering Components 
ReactDOM.render(<Login/>,document.getElementById('test'))

6.2 Uncontrolled components

characteristic : Enter the cash in and cash out

// Create components 
class Login extends React.Component{
    
	handleSubmit = (event)=>{
    
		event.preventDefault() // Block form submission 
		const {
    username,password} = this
		alert(` The user name you entered is :${
      username.value}, The password you entered is :${
      password.value}`)
	}
	render(){
    
		return(
			<form onSubmit={
    this.handleSubmit}>
				 user name :<input ref={
    c => this.username = c} type="text" name="username"/>
				 password :<input ref={
    c => this.password = c} type="password" name="password"/>
				<button> Sign in </button>
			</form>
		)
	}
}
// Rendering Components 
ReactDOM.render(<Login/>,document.getElementById('test'))

7、 ... and 、 Higher order function —— The function is coriolized

Higher order function : If a function conforms to the following 2 Any one of the specifications , Then the function is a higher-order function

  1. if A function , The received parameter is a function , that A It's called a higher-order function
  2. if A function , The return value of the call is still a function , that A It's called a higher-order function

Common higher-order functions are :Promise、setTimeout、arr.map() wait

The coriolisation of functions : adopt The function call continues to return the function The way , Realize the function coding form of multiple received parameters and finally unified processing

function sum(a){
    
	return(b)=>{
    
		return (c)=>{
    
			return a+b+c
		}
	}
}

Take the above collection form data as an example :

// Save form data to state 
//  according to  data  Type of return  event.target.value
saveFormData = (dataType)=>{
    
	return (event)=>{
    
		this.setState({
    [dataType]:event.target.value})
	}
}

//  Don't use Curry's writing 
saveFormData = (dataType,event)=>{
    
	this.setState({
    [dataType]:event.target.value})
}

8、 ... and 、 Life cycle of components

8.1 Understand life cycle

  1. A component goes through some specific stages from creation to death
  2. React The component contains a series of hook functions ( Life cycle callback function , It can be understood as hooking out this function when necessary ), Will call... At a specific time ( Life cycle callback function <=> Life cycle hook function <=> Life cycle function <=> Lifecycle hook )
  3. When we define components , In a specific lifecycle callback function , Do a specific job

8.2 Life cycle flowchart ( used )

Three stages of the life cycle ( used )

  1. Initialization phase : from ReactDOM.render() Trigger — First rendering
    1.constructor(): Constructors
    2.componentWillMount(): The hook on which the component will be mounted
    3.render(): One that must be used
    4.componentDidMount(): Hook after component mounting , Usually do some initialization in this hook , for example : Turn on timer 、 Send network request 、 Subscribe to news

  2. Update phase : From within the component this.setSate() Or the parent component restarts render Trigger
    1.shouldComponentUpdate(): Controls the of component updates “ valve ”, The return value is true I'm going to continue ,false Then directly interrupt , If you don't write , The default return value of the bottom layer is true

    2.componentWillUpdate(): The hook that the component will update
    3.render()
    4.componentDidUpdate(): Hook after component update

  3. Uninstall components : from ReactDOM.unmountComponentAtNode() Trigger
    1.componentWillUnmount(): The hook that the component will unload , Usually do some finishing work in this hook , for example : off timer 、 Unsubscribe from messages

8.3 Life cycle ( used ) give an example

// Create components 
class Count extends React.Component{
    
	// Constructors 
	constructor(props){
    
		console.log('Count---constructor');
		super(props)
		// Initialization status 
		this.state = {
    count:0}
	}
	// Add 1 Button callback 
	add = ()=>{
    
		// Get the original state 
		const {
    count} = this.state
		// Update status 
		this.setState({
    count:count+1})
	}

	// Callback of unload component button 
	death = ()=>{
    
		ReactDOM.unmountComponentAtNode(document.getElementById('test'))
	}
	// Force the callback of the update button 
	force = ()=>{
    
		this.forceUpdate()
	}
	// The hook on which the component will be mounted 
	componentWillMount(){
    
		console.log('Count---componentWillMount');
	}
	// Hook after component mounting 
	componentDidMount(){
    
		console.log('Count---componentDidMount');
	}
	// The hook that the component will unload 
	componentWillUnmount(){
    
		console.log('Count---componentWillUnmount');
	}
	// Controls the of component updates “ valve ”
	shouldComponentUpdate(){
    
		console.log('Count---shouldComponentUpdate');
		return true
	}
	// The hook that the component will update 
	componentWillUpdate(){
    
		console.log('Count---componentWillUpdate');
	}
	// Hook after component update 
	componentDidUpdate(){
    
		console.log('Count---componentDidUpdate');
	}
	render(){
    
		console.log('Count---render');
		const {
    count} = this.state
		return(
			<div>
				<h2> The current sum is :{
    count}</h2>
				<button onClick={
    this.add}> Am I +1</button>
				<button onClick={
    this.death}> Uninstall components </button>
				<button onClick={
    this.force}> Do not change the data in any state , Forced update </button>
			</div>
		)
	}
}

8.4 Life cycle flowchart ( new )

The difference between old and new life cycles :

  1. Abolish the three hooks of the old life cycle : componentWillMount、 componentWillReceiveProps and
    componentWillUpdata
  2. Two new hooks : getDerivedStateFromProps and getSnapshotBeforeUpdate
    1.getDerivedStateFromProps: from props Get derived from state, namely state Value depends at all times props
    2.getSnapshotBeforeUpdate: Take a snapshot before updating the component , The return value can be of any type

8.5 Important hooks

  1. render: Initialize rendering or update rendering calls
  2. componentDidMount: Turn on monitoring , send out ajax request
  3. componentWillUnmount: Do some finishing work , Such as : Clear timer

8.6 A hook about to be discarded

  1. componentWillMount
  2. componentWillReceiveProps
  3. componentWillUpdate

These hooks have will, A warning will appear now , The next big version needs to add UNSAFE_ Prefix can be used , It may be completely abandoned in the future , Not recommended

Nine 、 fictitious DOM And DOM Diffing Algorithm

9.1 Basic schematic diagram

 Insert picture description here

9.2 Add :key The role of

Classic interview questions :

  1. react/vue Medium key What's the role ?(key What is the internal principle of ?)
  2. Why when traversing a list ,key It's better not to use it index?
1. fictitious DOM in key The role of :
	(1) To put it simply : key Is a virtual DOM Identification of the object ,  When updating the display key Plays an extremely important role 
	(2) Say in detail :  When the data in the state changes ,react Will be based on 【 The new data 】 Generate 【 New virtual DOM】,  And then React Conduct 【 New virtual DOM】 And 【 Old virtual DOM】 Of diff Compare , The comparison rules are as follows :
		a.  Old virtual DOM Found with the new virtual DOM same key:
			a1. If virtual DOM The content in the has not changed ,  Directly use the previous reality DOM
			a2. If virtual DOM The content has changed ,  Then a new reality is generated DOM, Then replace the previous real... In the page DOM
		b.  Old virtual DOM The new virtual machine was not found in DOM same key:
			 Create a new reality based on the data DOM, Then render to the page 

2. use index As key Problems that may arise :
	(1) If the data is : Add in reverse order 、 Reverse order deletion and other destructive operations :
		 It creates unnecessary reality DOM to update  ==>  The interface effect is OK ,  But low efficiency 
	(2) If the structure also contains... Of the input class DOM:
		 There will be mistakes DOM to update  ==>  There is a problem with the interface 
	(3) Be careful ! If there is no reverse order addition to the data 、 Reverse order deletion and other destructive operations , For rendering only, the list is used to show , Use index As key There is no problem 

3. How to choose key:
	(1) It is best to use the unique identification of each data as key,  such as id、 cell-phone number 、 ID number 、 Unique value such as student number 
	(2) If you're sure it's just a simple display of data , use index It's OK, too 

React Series summary :

React Summary of learning ( One )

copyright notice
author[APythonC],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201262352576528.html

Random recommended