Class component details

Posted by newcastle_unite on Wed, 18 Mar 2020 09:54:50 +0100

1, class component creation method

import React from 'react';

class B extends React.Component {
  constructor(props){
    super(props);
  }
  render(){
    return (
      <div>hi</div>
    )
  }
}

2, Props external data

class Parent extends React.Component {
  constructor(props){
    super(props)
    this.state = {name:'frank'}
  }
  onClick = ()=>{}
  render(){
    return <B name={this.state.name} onClick={this.onClick}>hi</B>
  } // The name and onClick here are props. The source is from this.state. They are from the outside as props
}

// How to initialize props? After this is done, this.props is the object address of external data
class B extends React.Component {
  constructor(props){
    super(props);
  }
  render(){

  }
}

// Read props
class B extends React.Component {
  constructor(props){
    super(props);
  }
  render(){
    return <div onClick={this.props.onClick}>
      {this.props.name}
      <div>
        {this.props.children}
      </div>
    </div>
  }
}

// Cannot write props, external data should be updated by external

3, The role of component will receive props

  • Receive external data, which can only be read but not written. The external data is passed by the parent component
  • Accept the external function and call it at the right time, which is generally the function of the parent component
import React from 'react';

class App extends React.Component {
  constructor(props){
    super(props)
    this.state = {x : 1}
  }

  onClick = () => {
    this.setState({
      x: this.state.x + 1
    })
  }

  render(){
    return (
      <div className="App">
        App <button onClick={this.onClick}>+1</button>
        <B name={this.state.x}/>
      </div>
    );
  }
}

class B extends React.Component {
  UNSAFE_componentWillReceiveProps(newProps, nextContext) {
    console.log('Old props')
    console.log(this.props)
    console.log('props Changed')
    console.log('New p props')
    console.log(newProps)
  }
  render(){
    return (
      <div>{this.props.name}</div>
    )
  }
}

export default App;

4, State & setstate internal data

  • Initialize State
class B extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      user: {name:'frank', age:187}
    }
  }
  render(){

  }
}
  • The two methods of setState are recommended to be written as a function. Generally, the first parameter and the second parameter are used to accept the callback function after success. In addition, when the state is written, there will be a shallow merge
  onClick = () => {
    this.setState({
      x: this.state.x + 1
    })
    this.setState({
      x: this.state.x + 1
    })
  }

  onClick2 = () => {
    this.setState((state)=>({x:state.x+1}))
    this.setState((state)=>({x:state.x+1}))
  }

5, Life cycle

let div = document.createElement('div')
// This is the create/construct process of div
div.textContent = 'hi'
// This is initialization state
document.body.appendChild(div)
// This is the mount process of div
div.textContent = 'hi2'
// This is the update process of div
div.remove()
// This is the unmount process of div
  • The following is a list of common functions
constructor() - initialize state here
 shouldComponentUpdate() - return false block updates
 render() - create virtual DOM
 componentDidMount() - component appears on page
 componentDidUpdate() - component updated
 componentWillUnmount() - component will die
  • Use of constructor
    • Initialize props
    • Initialize state, but setState cannot be called at this time
    • Used to write bind this
        constructor(){
            this.onClick = this.onClick.bind(this)
        }
        Can be replaced by new grammar
        onClick = ()=> {}
        constructor() {
      
        }
      
    • Disdain
  • Use of shouldComponentUpdate
    • Return true to not block UI updates
    • Return false to block UI updates
    • See next page for example
    • Interviewers often ask: what's the use of shouldComponentUpdate?
    • Answer: it allows us to manually determine whether to update components. We can flexibly set the return value according to the application scenario to avoid unnecessary updates
  • React.PureComponent will make a shallow comparison between state and props, so shouldComponentUpdate is not needed
  • Purpose of render
    • Presentation view,
    // The object corresponding to return is not a DOM element, but an object representing the DOM element. We call it virtual dom 
    return (<div>...</div>)
    
    • There can only be one root element
    Use React.Fragment as placeholder, or write it as < > < / > and they are equivalent
    
    • Skill
    // render can write if...else
    // Can you write?
    // Cannot write for directly, array is required
    // You can write array.map 
    
    import React from 'react';
    
    class App extends React.PureComponent {
      constructor(props){
        super(props)
        this.state = {
          n:1
        }
      }
      onClick= ()=>{
        this.setState(state=> ({
          n: state.n+1
        }))
      }
    
      render(){
        console.log('render Once.')
        let message
        if(this.state.n % 2 === 0 ) {
          message = <div>Even numbers</div>
        } else {
          message = <span>Odd number</span>
        }
        return (
          <>
            {message}
            <button onClick={ this.onClick }>+1</button>
          </>
        )
      }
    }
    
    export default App;
    // The writing of circulation
    render() {
      return this.state.array.map(n=><span key={n}>{n}</span>)
    }
    
    • Use of componentDidMount()
      • Execute code after the element is inserted into the page, which depends on DOM
      • For example, if you want to get the height of a div, you'd better write it here
      • Here you can initiate an AJAX request to load data (official recommendation)
      • This hook will be executed in the first rendering
      componentDidMount() {
      const div = document.getElementById('xxx')
      const {width} = div.getBoundingClientRect()
      // console.log(width)
      this.setState({width})
      }
      
      render(){
        return(
          <div id='xxx'>Hello World, {this.state.width}
          </div>
        )
      }
      
      • You can also do it with ref
        import React from 'react';
        
        class App extends React.PureComponent {
          constructor(props){
            super(props)
            this.state = {
              n:1,
              width: undefined
            }
            this.divRef = React.createRef()
          }
          onClick= ()=>{
            this.setState(state=> ({
              n: state.n+1
            }))
          }
        
          componentDidMount() {
            const div = this.divRef.current
            const {width} = div.getBoundingClientRect()
            // console.log(width)
            this.setState({width})
          }
        
          render(){
            return(
              <div ref={this.divRef}>Hello World, {this.state.width}px
              </div>
            )
          }
        }
        
        export default App;
        
        
    • The function of componentDidUpdate()
      • Execute code after view update
      • AJAX requests can also be initiated here to update data (see documentation)
      • This hook will not be executed in the first rendering
      • In this case, setState may cause infinite loop unless it is placed in if
      • If componentDidUpdate returns false, this hook will not be triggered
    • Use of componentWillUnmount
    • Code to be executed when the component is to be removed from the page and then destroyed
    • Unmounted components will not mount again
    • Give an example:
    If you listen to window scroll in component didmount
     Then it is necessary to cancel listening in the purpose of component will unmount
     If you create a Timer in component didmount
     Then cancel Timer in component will unmount
     If you create an AJAX request in component didmount, this is a special case. You die before the data comes back 
    Then cancel the request in component will unmount
    
    • Conclusion:
      • If you can use function components, you can use function components. If you can use purecomponent, you can use purecomponent. Finally, you can't use react.component
      • Life cycle function

Finally, personal wechat, welcome to exchange and provide job opportunities.

This article is based on the platform of blog one article multiple sending OpenWrite Release!

Topics: Front-end React Fragment