react 16.7 类组件使用指南

104 阅读3分钟

类组件的生命周期的应用场景

生命周期.jpg

  1. constructor:在组件创建时调用,用于 初始化组件的状态和绑定方法 。这是唯一一个在组件挂载之前调用的生命周期函数。通常用于初始化状态、绑定方法、或者进行其他一次性的设置。
    • 初始化 state
  2. render :
  3. componentDidMount: 在组件挂载后调用,通常用于进行一次性的操作,如数据获取、订阅事件、或者进行 DOM 操作
  4. shouldComponentUpdate(nextProps, nextState)在组件接收到新的 props 或 state 时调用,用于控制组件是否重新渲染。可以根据新的 props 或 state 与当前的 props 和 state 进行比较,从而确定是否需要重新渲染
    • nextProps, nextState 是修改后的 props和 state
    • 通过 this.props 和 this.state 可以获取到旧的 props和 state
    • 如果 shouldComponentUpdate 返回 true,React 将继续执行组件的更新过程。如果返回 false,React 将阻止组件更新,即不会调用 render 方法、componentDidUpdate 方法等,也不会引发子组件的更新
  5. componentDidUpdate(prevProps, prevState, snapshot): 在组件更新后调用,通常用于在组件更新后执行一些操作,如更新 DOM、处理动画效果
    • prevProps, prevState 是修改前的 props和 state
    • 通过 this.props 和 this.state 可以获取修改后到的 props和 state
    • snapshot 是 getSnapshotBeforeUpdate的返回值
  6. componentWillUnmount: 在组件卸载前调用,通常用于清理工作,如取消订阅、清除定时器、或释放资源
  7. getDerivedStateFromProps(nextProps, prevState)
    • 作用: 用于派生出一个新的状态对象,该状态对象将与当前 state 进行合并。
    • 用法场景: 通常在组件的 state 需要根据新的 props 计算而来时使用。它是在组件挂载时和接收到新的 props 时都会被调用的生命周期方法。
  8. getSnapshotBeforeUpdate
    • 作用: 在最近一次渲染输出(提交到 DOM 上)之前捕获一些信息,该信息将作为参数传递给 componentDidUpdate。
    • 用法场景: 通常用于获取 DOM 相关信息,如滚动位置等,以便在 componentDidUpdate 中使用。
    • 语法:
    getSnapshotBeforeUpdate(prevProps, prevState) {
      // 返回一个值,将作为第三个参数传递给 componentDidUpdate
    }
    

props

  1. 使用 this.props

PropTypes-定义 props 数据类型

在 React 15.5 版本之前,PropTypes 是内置于 React 包中的,但自 React 15.5 版本起,它被移动到了一个单独的 prop-types 包中。你可以通过安装该包来使用 PropTypes

  1. 安装:npm install prop-types
  2. 使用:
import PropTypes from 'prop-types';

MyComponent.propTypes = {
  user: PropTypes.object
};

defaultProps-为组件的属性(props)提供默认值

  1. 使用:
MyComponent.defaultProps = {
  title: 'Default Title',
  count: 0
};

state

  1. 定义state
state = {
	age: 1,
	name: 11,
}
  1. 在 constructor 中进行初始化
constructor(){
    super()
    this.state.other = {
        address: 'China'
    }
}
  1. 修改state:使用setState方法将修改后的数据传进去就可以了
this.setState({ age: 10 })

refs

能不用最好不用

  1. 定义refs
    • 字符串形式的ref: <input ref="input1"/>
    • 回调形式的ref: <input ref={(c)=>{this.input1 = c}}/>
    • createRef创建ref容器: input1 = React.createRef();<input ref={this.input1}/>
  2. 类组件使用refs 获取组件实例
class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    // 创建一个 ref 对象
    this.myChildComponentRef = React.createRef();
  }

  componentDidMount() {
    // 在组件挂载后,可以通过 this.myChildComponentRef.current 获取对子组件实例的引用
    this.myChildComponentRef.current.someMethod();
  }

  render() {
    return (
      <ChildComponent ref={this.myChildComponentRef} />
    );
  }
}

class ChildComponent extends React.Component {
  someMethod() {
    // 子组件的方法
  }

  render() {
    return (
      // 子组件的渲染
    );
  }
}

响应原理