React component communication (study notes)

Introduction to Component Communication

  • Components are self-contained and closed units that, by default, can only use their own data.
  • In the componentization process, we split a complete function into multiple components to better complete the functions of the entire application. In this process, it is impossible to avoid sharing some data between multiple components .
  • In order to realize these functions, it is necessary to break the independent closure of components and let them communicate with the outside world. This process is called component communication

component props

  • Components are closed, and to accept external data should be implemented through props
  • The role of props: receive data passed to the component
  • Pass data: add attributes to component tags
  • Accept data: function components accept data through parameter props , class components accept data through this.props

Features

  1. Any type of data can be passed to components (functions, arrays, JSX...)
  2. props is a read-only object, only the value of the property can be read, and the object cannot be modified
  3. Note: When using class components, if a constructor is written, props should be passed to super() , otherwise, props cannot be obtained in the constructor!

Three ways of component communication

There are 3 types of communication between components:

  1. Parent Component -> Child Component
  2. child component -> parent component
  3. sibling component

Parent component passes data to child component

  1. The parent component provides the state data to be passed
  2. Add an attribute to the child component label, the value is the data in the state
  3. The child component accepts the data passed in the parent component through props

Child component passes data to parent component

Ideas: Using the callback function, the parent component provides the callback, the child component calls, and the data to be passed is used as the parameter of the callback function.

  1. The parent component provides a callback function (for accepting data)
  2. Pass the function as the value of the property to the child component
  3. 子组件通过props调用回调函数
  4. 将子组件的数据作为参数传递给回调函数

兄弟组件

  • 共享状态提升到最近的公共父组件中,由公共父组件管理这个状态
  • 思想:状态提升
  • 公共父组件的职责: 1. 提供共享状态 2. 提供操作共享状态的方法
  • 要通讯的子组件只需通过props接受状态或操作状态的方法

Context

思考:如何实现多层传递

  • 处理方式: 使用props一层一层组件往下传递(繁琐)
  • 更好的处理方式: 使用Context
    作用: 跨组件传递数据(比如主题、语言等)

使用步骤

  1. 调用React.createContext()创建Provider(提供数据)和Consumer(消费数据)两个组件
    const { Provider, Consumer } = React.createContext()

  2. 使用Provider组件作为父节点

<Provider>
   <div className="APP">
      <Child1 />
   </div>
</Provider>
复制代码
  1. 设置value属性,表示要传递的数据
    <Provider value="blue">
  2. 使用Consumer组件接受数据
<Consumer>
   {data => <span>data参数表示接收到的数据--{data}</span>}
</Consumer>
复制代码

总结

  1. 如果两个组件嵌套多层,可以使用Context实现组件通讯
  2. Context提供了两个组件:Provider和Consumer
  3. Provider组件:用来提供数据
  4. Consumer组件:用来消费数据

props其他知识点

children属性

  • children属性:表示组件标签的子节点。当组件标签有子节点时,props就会有该属性
  • children属性和普通的props一样,值可以是任意值(react元素,函数,组件)

props校验

对于组件来说,props是外来的,无法保证组件使用者传入什么格式的数据 如果传入的数据格式不对,可能会导致组件内部报错,关键问题:组件的使用者不知道明确的错误原因

  • props校验:允许在创建组件的时候,就指定props的类型、格式
  • 作用:捕获使用组件时因为props导致的错误,给出明确的错误提示,增加组件的健壮性,例App.propTypes = { colors: PropTypes.array }
使用步骤
  1. 安装包prop-types(yarn add prop-types/npm i props-types)
  2. 导入prop-types包 import PropTypes from 'prop-types'
  3. 使用组件名.propTypes = {}来给组件的props添加校验规则
  4. 校验规则通过PropTypes对象来指定
约束规则
  1. 常见类型:array、bool、func、number、object、string
  2. React元素类型:element
  3. 必填项:isRequired
  4. 特定结构的对象:shape({})
optionalObjectWithShape: PropTypes.shape({
   color: PropTypes.string,
   fontSize: PropTypes.number
})
复制代码

所有类型可查看 reactjs.org/docs/typech…

props的默认值
  • 场景:分页组件——>每页显示条数 App.defaultProps = { pageSize: 10}
  • 作用:给props设置默认值,在未传入props时生效

组件的生命周期

组件的生命周期概述

  • 意义: 组件的生命周期有助于理解组件的运行方式、完成更复杂的组件功能、分析组件错误原因等。
  • 组件的生命周期:组件从被创建到挂载到页面中运行,再到组件不用时卸载的过程。
  • 生命周期的每个阶段总是伴随着一些方法调用,这些方法就是生命周期的钩子函数。
  • 生命周期的作用:为开发人员在不同阶段操作组件提供了时期。
  • 只有 类组件 才有生命周期。

生命周期的三个阶段

  1. 每个阶段的执行时机
  2. 每个阶段钩子函数的执行顺序
  3. 每个阶段钩子函数的作用

创建时(挂载阶段)

  • 执行时机:组件创建时(页面加载时)
  • 执行顺序:
graph LR
Constructor --> Render --> ComponentDidMount
钩子函数 触发时机 作用
constructor 创建组件时,最先执行 1.初始化state
2.为事件处理程序绑定this
render 每次组件渲染都会触发 渲染UI(注意:不能调用setState())
componentDidMount 组件挂载(完成DOM渲染)后 1.发送网络请求
2.DOM操作

更新时(更新阶段)

  • 执行时机:1.setState() 2.forceUpdate() 3.组件接收到新的props
  • 说明:以上三者任意一种变化,组件就会重新渲染
  • 执行顺序:
graph LR
Render --> ComponentDidUpdate
钩子函数 触发时机 作用
render 每次组件渲染都会触发 渲染UI(注意:不能调用setState())
componentDidUpdate 组件更新(完成DOM渲染)后 1.发送网络请求
2.DOM操作
3.注意:如果要setState()必须放在一个if条件中
比较更新前后的props是否相同
conponentDidUpdate(prevProps){
   if(prevProps.count !== this.props.count) {
      this.setState({})
}
复制代码

卸载时(卸载阶段)

  • 执行时机:组件从页面中消失
钩子函数 触发时机 作用
componentWillUnmount 组件卸载(从页面中消失) 执行清理工作(比如:清理定时器等)

不常用钩子函数介绍

  • getDerivedStateFromProps
  • getSnapshotBeforeUpdate
  • shouldComponentUpdate

Guess you like

Origin juejin.im/post/7012974779573469197