React(精读官方文档) -API REFERENCE - React.Component(生命周期、render、Error boundaries、setState、forceUpdate等)

概览

  • React 的组件可以定义为 class 或函数的形式
  • 如需定义 class 组件,需要继承 React.Component
  • 在 React.Component 的子类中有个必须定义的 render() 函数
  • 强烈建议不要创建自己的组件基类;在 React 组件中,代码重用的主要方式是组合而不是继承
    class Welcome extends React.Component {
      render() {
        return <h1>Hello, {this.props.name}</h1>;
      }
    }
    

组件的生命周期

  • 挂载:当组件实例被创建并插入 DOM 中时,其生命周期调用顺序如下:
    • constructor()
    • static getDerivedStateFromProps()
    • render()
    • componentDidMount()
  • 更新: 当组件的 props 或 state 发生变化时会触发更新。组件更新的生命周期调用顺序如下:
    • static getDerivedStateFromProps()
    • shouldComponentUpdate()
    • render()
    • getSnapshotBedoreUpdate()
    • componentDidUpdate()
  • 卸载:当组件从 DOM 中移除时会调用如下方法:
    • componentWillUnmount()
  • 错误处理:当渲染过程,生命周期,或子组件的构造函数中抛出错误时,会调用如下方法:
    • static getDerivedStateFromError()
    • componentDidCatch()

render()

  • render() 方法是 class 组件中唯一必须实现的方法
  • 当 render 被调用时,它会检查 this.props 和 this.state 的变化并返回以下类型之一:
    • React元素
    • 数组 或 fragements
    • Portals
    • 字符串 或 数值类型
    • 布尔类型 或 null
  • render() 函数应该为纯函数,这意味着在不修改组件 state 的情况下,每次调用时都返回相同的结果

constructor()

  • 如果不初始化 state 或不进行方法绑定,则不需要为 React 组件实现构造函数。
  • 通常,在 React 中,构造函数仅用于以下两种情况:
    • 初始化 state
    • 为事件处理函数绑定实例
  • 应在其他语句之前调用 super(props)。否则,this.props 在构造函数中可能会出现未定义的 bug。
  • 注意:避免将 props 的值复制给 state!
    constructor(props) {
        super(props);
        // 不要在这里调用 this.setState()
        this.state = { counter: 0 };
        this.handleClick = this.handleClick.bind(this);
    }
    

componentDidMount()

  • 会在组件挂载后(插入 DOM 树中)立即调用
  • 依赖于 DOM 节点的初始化应该放在这里
  • 也可以用于通过网络请求获取数据、添加订阅
    componentDidMount()
    

componentDidUpdate()

 componentDidUpate(prevProps,prevState,snapshot)
  • 在更新后会被立即调用。首次渲染不会执行此方法。
  • 如果组件实现了 getSnapshotBeforeUpdate() 生命周期(不常用),则它的返回值将作为 componentDidUpdate() 的第三个参数 “snapshot” 参数传递。否则此参数将为 undefined
  • 如果 shouldComponentUpdate() 返回值为 false,则不会调用 componentDidUpdate()

componentWillUnmount()

  • 在组件卸载及销毁之前直接调用
  • 在此方法中执行必要的清理操作,例如,清除 timer,取消网络请求或清除在 componentDidMount() 中创建的订阅等
  • componentWillUnmount() 中不应调用 setState()

shouldComponentUpdate()

shouldComponentUpdate(nextProps, nextState)
  • 当 props 或 state 发生变化时,shouldComponentUpdate() 会在渲染执行之前被调用。返回值默认为 true
  • 如果 shouldComponentUpdate() 返回 false,则不会渲染
  • 首次渲染或使用 forceUpdate() 时不会调用该方法。
  • 仅作为性能优化的方式而存在。可以优先考虑使用内置的 PureComponent 组件,而不是手动编写 shouldComponentUpdate()

Error boundaries

  • React 组件
  • 在其子组件树中的任何位置捕获 JavaScript 错误,并记录这些错误,展示降级 UI 而不是崩溃的组件树
  • 仅使用 Error boundaries 组件来从意外异常中恢复的情况;不要将它们用于流程控制
  • 如果 class 组件定义了生命周期方法 static getDerivedStateFromError() 或 componentDidCatch() 中的任何一个(或两者),它就成为了 Error boundaries

static getDerivedStateFromError()

  • 此生命周期会在后代组件抛出错误后被调用。 它将抛出的错误作为参数,并返回一个值以更新 state
    class ErrorBoundary extends React.Component {
      constructor(props) {
        super(props);
        this.state = { hasError: false };
      }
    
      static getDerivedStateFromError(error) {
        // 更新 state 使下一次渲染可以显降级 UI
        return { hasError: true };
      }
    
      render() {
        if (this.state.hasError) {
          // 你可以渲染任何自定义的降级  UI
          return <h1>Something went wrong.</h1>;
        }
    
        return this.props.children; 
      }
    }
    
  • 注意:getDerivedStateFromError() 会在渲染阶段调用,因此不允许出现副作用。 如遇此类情况,请改用 componentDidCatch()

componentDidCatch()

   componentDidCatch(error, info)
  • error —— 抛出的错误。
  • info —— 带有 componentStack key 的对象,其中包含有关组件引发错误的栈信息。
  • componentDidCatch() 会在“提交”阶段被调用,因此允许执行副作用

setState()

setState(updater, [callback])
  • 用于更新state

  • React 会延迟调用它,然后通过一次传递更新多个组件,不保证立刻生效

  • 使用 componentDidUpdate 或者 setState 的回调函数(setState(updater, callback)),这两种方式都可以保证在应用更新后触发

  • 第一个参数:updater

    • 参数形式
    (state, props) => stateChange
    
    this.setState((state, props) => {
        return {counter: state.counter + props.step};
      });
      //updater 函数中接收的 state 和 props 都保证为最新。updater 的返回值会与 state 进行浅合并
    
    • 对象形式
    setState(stateChange[, callback])
    
    this.setState({quantity: 2})
    
  • 第二个参数:回调函数

    • 为可选的回调函数,它将在 setState 完成合并并重新渲染组件后执行。通常,我们建议使用 componentDidUpdate() 来代替此方式

forceUpdate()

component.forceUpdate(callback)
  • forceUpdate() 强制让组件重新渲染
  • 调用 forceUpdate() 将致使组件调用 render() 方法,此操作会跳过该组件的 shouldComponentUpdate()。但其子组件会触发正常的生命周期方法,包括 shouldComponentUpdate() 方法。如果标记发生变化,React 仍将只更新 DOM。
  • 应该避免使用 forceUpdate(),尽量在 render() 中使用 this.props 和 this.state。

class属性

defaultProps
  • defaultProps 可以为 Class 组件添加默认 props。这一般用于 props 未赋值,但又不能为 null 的情况
class CustomButton extends React.Component {
  // ...
}

CustomButton.defaultProps = {
  color: 'blue'
};
//如果未提供 props.color,则默认设置为 'blue'
  render() {
    return <CustomButton /> ; // props.color 将设置为 'blue'
  }
 //如果 props.color 被设置为 null,则它将保持为 null
   render() {
    return <CustomButton color={null} /> ; // props.color 将保持是 null
  }
displayName
  • displayName 字符串多用于调试消息
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值