Props for the component

  • Props is used to receive data passed to the component
  • Pass data to add attributes to component tags
class App extends React.Component {
    state = {
        userName: 'yusongH'
    }

    render() {
        return (
            <div>
                <ComComponent txt="Hello?" userName={this.state.userName}></ComComponent>
            </div>)}}Copy the code
  • Receive data
    • Function components passParameters of the propsReceive data
    function ComComponent(props) {
        return (
            <div>
                <div>txt:{props.txt}</div>
                <div>userName:{props.userName}</div>
            </div>)}Copy the code
    • Class component throughthis.porpsReceive data
    class ComComponent extends React.Component {
        render() {
            return (
                <div>
                    <div>txt:{this.props.txt}</div>
                    <div>userName:{this.props.userName}</div>
                </div>)}}Copy the code
  • conclusion
    • You can pass any type of data to a component
    • Props isread-onlyObject, can only read the value of the property, modify the error
    • Note: When using a class component, if you write a constructor, you should pass props to super(), otherwise you cannot get props in the constructor
    constructor(props) {
        super(props)
    
        console.log(this.props)
        console.log(props)
    }
    Copy the code

Three ways of component communication

  • Parent component -> Child component

    • Add attributes to child component tags with values of data in state
    class App extends React.Component {
        render() {
            return (
                <div>
                    <ComComponent txt="Hello?" userName={this.state.userName}></ComComponent>
                </div>)}}Copy the code
    • The child component receives data passed in the parent component through props
    class ComComponent extends React.Component {
        render() {
            return (
                <div>
                    <div>txt:{this.props.txt}</div>
                    <div>userName:{this.props.userName}</div>
                </div>)}}Copy the code
  • Child component -> Parent component

    • The parent component provides the callback, and the child component calls the callback, passing the data that needs to be passed as an argument to the callback function
    • Note: The this of the callback that gets the argument points to the problem
    / / the parent component
    class ParentComponent extends React.Component {
        state = {
            childMsg: ' '
        }
        // Receive the value callback function
        getChildMsg = (data) = > {
            console.log('Arguments passed by the parent:', data)
            // Note the direction of this, so use the arrow function
            console.log(this)
            this.setState({
                childMsg: data
            })
        }
        render() {
            return (
                <div>
                    <div>The parent component</div>
                    <div>Child component passes data: {this.state.childmsg}</div>
                    <ChildComponent getMsg={this.getChildMsg}></ChildComponent>
                </div>)}}/ / child component
    class ChildComponent extends React.Component {
        state = {
            msg: 'Data to parent component data'
        }
    
        handleClick = () = > {
            // Invoke the callback provided by the parent component
            this.props.getMsg(this.state.msg)
        }
    
        render() {
            return (
                <div>
                    <div>Child components</div>
                    <button onClick={this.handleClick}>Click Pass data to the parent component</button>
                </div>)}}Copy the code
  • Brother components

    • State promotion: Promotes the shared state to the nearest public parent, which manages the state
    • Common parent components: 1. Provide the state of the shares; 2. Provide methods to manipulate the state of those shares
    • A child component to communicate simply needs methods to receive state or operation state through props
    class BrotherComponent extends React.Component {
        state = {
            count: 0
        }
    
        // Provide the child component to change the state
        changeCount = () = > {
            // Change the status
            this.setState({
                count: this.state.count + 1})}render() {
            return (
                <div>
                    <FirstChildComponent count={this.state.count} />
                    <SecondChildComponent changeCount={this.changeCount} />
                </div>)}}class FirstChildComponent extends React.Component {
        render() {
            return (
                <div>Counter: {this.props. Count}</div>)}}class SecondChildComponent extends React.Component {
        handleClick = () = > {
            this.props.changeCount()
        }
    
        render() {
            return (
                <button onClick={this.handleClick}>+ 1</button>)}}Copy the code

Context basic use

Purpose: Transfer values across components

Using the step

  • Call React. CreateContext () to create the Provider and Consumer components
// Create context, Provider, Consumer
const { Provider, Consumer } = React.createContext()
Copy the code
  • Use the Provider component as the parent node
class ContextComponent extends React.Component {

    render() {
        return (
            // Use Provider packages to pass values through value
            <Provider value="hello, child">
                <div>
                    contextComponent
                    <Node />
                </div>
            </Provider>)}}Copy the code
  • Sets the value property to represent the data to be passed
class ContextComponent extends React.Component {

    render() {
        return (
            // Use Provider packages to pass values through value
            <Provider value="hello, child">
                <div>
                    contextComponent
                    <Node />
                </div>
            </Provider>)}}Copy the code
  • The data is received through the Consumer component, where callback functions are defined
class Node extends React.Component {
    render() {
        return (
            <div>
                node
                <SubNode />
            </div>)}}class SubNode extends React.Component {

    render() {
        return (
            <div>
                subNode
                <Child />
            </div>)}}class Child extends React.Component {

    render() {
        return (
            // Use the Consumer package to define the callback to receive data
            <Consumer>
                {
                    data => <div>Child :contextComponet -- {data}</div>
                }
            </Consumer>)}}Copy the code

Five, porPS in-depth

Children attribute

  • Represents the child node of the component label, which is used when the component label has a sub node
  • The children attribute, like ordinary props, can have any value (text, React element, component, function)
class PropsDeep extends React.Component {

    render() {
        return (
            <div>
                parent
                <Child>Child nodes</Child>
            </div>)}}class Child extends React.Component {
    render() {
        return (
            <div>
                child ---
                {this.props.children}
            </div>)}}Copy the code

Props check

  • The props are external to the component. There is no guarantee of the format of the data passed by the component user, so it needs to be verified
  • Props verification: Allows you to specify the type, format, and so on of props when creating a component

Using the step

  • NPM I PORp-types/YARN add prop-types
  • Import prop – types package
  • useComponent name. PropTypes = {}To add validation rules to the component props
  • Validation rules are specified by the PropType object
  • Constraint rules
    • Common types are array, bool, func, number, object, and String
    • React Element type: Element
    • Required: isRequired
    • Object of specific structure: Shape ({})
    PropsCheck.propTypes = {
        // The type of the num attribute is number.
        num: PropTypes.number,
        // The type of attribute fn is a function (func) and must be passed
        fn: PropTypes.func.isRequired,
        // Type of attribute tag: React element (element)
        tag: PropTypes.element,
        {userName: 'yusong', age: 18}}
        obj: PropTypes.shape({
            userName: PropTypes.string,
            age: PropTypes.number
        })
    }
    Copy the code

Component life cycle

Only class components (stateful components) have a life cycle

Creation time (mount phase)

Execution timing: Component creation (page loading)

Order of execution:

  • constructor()
    • When a component is created, it is executed first
    • Function:
      • Initialize the state
      • Bind this to the event handler
  • render()
    • This will trigger every time a valence render is performed
    • role
      • Rendering UI (SetState () cannot be called, as it would cause recursion)
  • componentDidMount()
    • Component mount (after DOM rendering is complete)
    • role
      • Sending network Requests
      • DOM manipulation
Hook function trigger role
constructor When a component is created, it is executed first 1. Initialize state

Bind this to the time handler
render This will trigger every time a valence render is performed Rendering UI (SetState () cannot be called, as it would cause recursion)
componentDidMount Component mount (after DOM rendering is complete) 1. Send network requests

2. DOM manipulation

Update time (Update phase)

Execution time:

  • Call setState ()
  • Call forceUpdate ()
  • The component receives the new props

Execution order

  • render()
    • Fires every time a component is rendered
    • role
      • Render UI (same render as mount stage)
  • componentDidUpdate()
    • Component update (after DOM rendering is complete)
    • role
      • Sending network Requests
      • DOM manipulation
      • Note: setState() must be placed in an if condition
      class LifeCycle extends React.Component {
          state = {
              count: 0,
          }
          changeCount = () = > {
              this.setState({
                  count: this.state.count + 1})},render() {
              return (
                  <div>
                      <Child1 count={this.state.count} />
                      <Child2 changeCount={this.changeCount} />
                  </div>)}}class Child1 extends React.Component {
          // prevProps props of the previous session
          componentDidUpdate(prevProps) {
              console.log('Updated', prevProps)
              // When you call setState() in a fixed hook, you must use a judgment condition, otherwise it will result in a recursive error
              // check whether the previous props is equal to the current props
              if(prevProps.count ! = =this.props.count) {
                  this.setState({})
              }
          }
          render() {
              return (
                  <div>Child1: {this. Props. Count}</div>)}}class Child2 extends React.Component {
          render() {
              return (
                  <div>
                      child2
                      <button onClick={()= > this.props.changeCount()}>+1</button>
                  </div>)}}Copy the code
Hook function trigger role
render Fires every time a component is rendered Render UI (same render as mount stage)
componentDidUpdate Component update (after DOM rendering is complete) 1. Send network requests

2. DOM manipulation

Note that setState() must be placed in an if condition

Unloading time (unloading stage)

Execution time

  • The component disappears from the page

Execution order

  • componentWillUnmount
    • Component unmount (disappear from page)
    • role
      • Perform cleanup (e.g., cleanup timer, etc.)
Hook function trigger role
componentWillUnmount Component unmount (disappear from page) Perform cleanup (e.g., cleanup timer, etc.)

Additional hook functions (more on this later)

Older full life cycle hooks

New version of full lifecycle hooks