Component Communication
- Components are independent, closed units, and by default, only the component’s own data can be used.
- In the componentization process, we divide a complete function into multiple components to better complete the function of the entire application. In this process, it is impossible to avoid sharing some data between multiple components.
- To achieve these functions, you need to break the isolation of the component and let it communicate with the outside world. This process is component communication
Components of the props
- Components are closed, and to accept external data should be implemented via props
- Props is used to receive data passed to the component
- Pass data: Add attributes to component tags
- Accept data: The function component accepts data through the props parameter, and the class component accepts data through this.props
The characteristics of
- You can pass any type of data to a component (functions, arrays, JSX…)
- Props is a read-only object that can only read the value of the property and cannot modify the object
- Note: When using a class component, if you write a constructor, you should pass props to super(). Otherwise, you cannot get props!
Components communicate in three ways
There are three types of communication between components:
- Parent component — > child component
- Child component — > Parent component
- Brother components
The parent component passes data to the child component
- The parent component provides the state data to be passed
- Add attributes to child component tags with values of data in state
- The child component accepts data passed in the parent component through props
The child component passes data to the parent
The parent component provides the callback, the child component calls it, and the data to be passed is the argument to the callback function.
- The parent component provides a callback function (to accept data)
- Pass this function as the value of the property to the child component
- The child component calls the callback function through props
- Pass the child component’s data as an argument to the callback function
Brother components
- Promote the shared state to the nearest public parent, which manages the state
- Thought: State ascending
- The responsibilities of the common parent component are: 1. Provide the shared state; 2. Provide methods to manipulate the shared state
- The child component to communicate simply accepts the state or the method of the operation state via props
Context
Consider: How to implement multi-layer delivery
- Handle: pass layers of components down using props (cumbersome)
- Use Context to pass data across components (topics, languages, etc.)
Using the step
-
Const {Provider, Consumer} = React. CreateContext () const {Provider, Consumer} = React. CreateContext ()
-
Use the Provider component as the parent node
<Provider>
<div className="APP">
<Child1 />
</div>
</Provider>
Copy the code
- Sets the value property to represent the data to be passed
<Provider value="blue">
- Use the Consumer component to accept data
<Consumer>
{data= > <span>The data argument represents the data received --{data}</span>}
</Consumer>
Copy the code
conclusion
- If two components are nested in multiple layers, you can use Context to implement component communication
- Context provides two components: Provider and Consumer
- Provider component: Used to provide data
- Consumer component: Used to consume data
Props
Children attribute
- Children property: Represents the children of the component label. Props has this property when the component tag has child nodes
- The children attribute, like ordinary props, can have any value (react element, function, component)
Props check
If the format of the data passed by the component user is incorrect, an error may occur in the component. Key questions: The user of the component does not know the cause of the error
- Props verification: Allows to specify the type and format of props when creating a component
- Function: To catch errors caused by props when using a component, and give clear error messages to increase the robustness of the component
App.propTypes = { colors: PropTypes.array }
Using the step
- Prop-types (YARN add prop-types/ NPM I props-types)
- Import prop – types package
import PropTypes from 'prop-types'
- use
Component name. PropTypes = {}
To add validation rules to the component props - Validation rules are specified through the PropTypes object
Constraint rules
- Common types are array, bool, func, number, object, and String
- React Element type: Element
- Mandatory: isRequired
- Object of specific structure: Shape ({})
optionalObjectWithShape: PropTypes.shape({
color: PropTypes.string,
fontSize: PropTypes.number
})
Copy the code
All types available at reactjs.org/docs/typech…
The default value for props
- Scenario: Paging component — > Number of entries per page
App.defaultProps = { pageSize: 10}
- Function: Set the default value for props, which takes effect when no props is passed
Component life cycle
Component lifecycle overview
- Meaning: The component lifecycle helps you understand how components work, perform more complex component functions, analyze component errors, and so on.
- Component life cycle: The process of creating a component, mounting it to a page, and uninstalling it when it is not in use.
- Each phase of the lifecycle is always accompanied by method calls that are the hook functions of the lifecycle.
- What the life cycle does: It provides a time period for developers to manipulate components in different phases.
- Only class components have a life cycle.
Three phases of the life cycle
- Timing of execution for each phase
- The order in which the hook functions are executed at each stage
- The role of the hook function at each stage
Creation time (mount phase)
- Execution timing: Component creation (page loading)
- Order of execution:
graph LR
Constructor --> Render --> ComponentDidMount
Hook function | trigger | role |
---|---|---|
constructor | When a component is created, it is executed first | 1. Initialize state 2. Bind this to the event handler |
render | Fires every time a component is rendered | Render UI(Note:Cannot call setState()) |
componentDidMount | After the component is mounted (DOM rendering is complete) | 1. Send a network request 2. DOM manipulation |
Update time (Update phase)
- SetState () 2. ForceUpdate () 3. The component receives the new props
- Note: If any of the above changes, the component will be re-rendered
- Order of execution:
graph LR
Render --> ComponentDidUpdate
Hook function | trigger | role |
---|---|---|
render | Fires every time a component is rendered | Render UI(Note:Cannot call setState()) |
componentDidUpdate | After the component is updated (DOM rendering is complete) | 1. Send a network request 2. DOM manipulation 3. Note that setState() must be placed in an if condition |
Check whether the props before and after the update are the sameconponentDidUpdate(prevProps){
if(prevProps.count ! = =this.props.count) {
this.setState({})
}
Copy the code
Unloading time (unloading stage)
- Execution time: Component disappears from the page
Hook function | trigger | role |
---|---|---|
componentWillUnmount | Component unmount (disappear from page) | Perform cleanup (e.g., cleanup timer, etc.) |
Introduction to hook functions that are not commonly used
- getDerivedStateFromProps
- getSnapshotBeforeUpdate
- shouldComponentUpdate