RN生命周期

2018-11-16  本文已影响0人  Jianjun_Zuo

安装的方法

当一个组件的实例被创建并被插入到DOM结构中,按下 constructor -> componentWillMount / getDerivedStateFromProps -> render -> componentDidMount 的顺序调用方法。

constructor(props, context)

关于ES6的class constructor和super,只要组件存在constructor, 就必要要写super, 否则this指向会错误。

constructor(props, context) {
  super(props, context)
  console.log(this.props, this.context) // 在内部可以使用props和context
}

componentWillMount()

该生命周期即将被遗弃,可以持续到 React 17 版本
执行的时机:
1、组件刚经历constructor,初始完数据
2、组件还未进入render,组件还未渲染完成,dom还未渲染

componentWillMount() {
}

static getDerivedStateFromProps(props, state)

React 16 版本加入的生命周期
执行的时机:
1、组件刚经历constructor,初始完数据
2、在 render 方法之前
3、必须有返回值,返回一个对象更新state,或者返回null

static getDerivedStateFromProps(props, state) {
  return { title: 'F2' }
}

render()

render方法是组件必须的方法。
当render方法被调用,将检查this.props 和 this.state,并且有一个返回值。
render方法的返回值类型如下:
React elements
在render中返回一个DOM节点。
通过JSX语法创建,例如:<View />,也可以是自己定义的组件<MyComponent />

render() {
  return (
    <View style={styles.container} />
  );
}

Arrays and fragments
可以在render方法中返回多个元素

render () {
  return (
    [
      <View style={{ flex: 1, backgroundColor: 'red' }} />,
      <View style={{ flex: 1, backgroundColor: 'blue' }} />
    ]
  )
}
render () {
  return (
    <React.Fragment>
      <View style={{ flex: 1, backgroundColor: 'red' }} />
      <View style={{ flex: 1, backgroundColor: 'blue' }} />
    </React.Fragment>
  )
}

Portals

String and numbers

Booleans or null

render () {
  return (
    true && <View style={{ flex: 1, backgroundColor: 'red' }} />
  )
}

render () {
  return (
    false && <View style={{ flex: 1, backgroundColor: 'red' }} />
  )
}

componentDidMount()

在组件安装完成后(组件实例插入到DOM树中)立即被调用。网络请求、设置监听等操作可以放到这个方法中。

方法的执行顺序

constructorcomponentWillMountrender的执行顺序:顶层父组件 -> 子组件 -> 子组件 ->...-> 底层子组件
componentDidMount执行顺序:底层子组件 -> 子组件 -> 子组件 ->...-> 顶层父组件

更新的方法

componentWillReceiveProps(nextProps)

static getDerivedStateFromProps()

同上

shouldComponentUpdate(nextProps, nextState)

在组件收到props或state发生变化时被调用。
默认返回true,表示要刷新组件。
在此方法中可以根据需要避免不必要的刷新。

render()

同上

componentWillUpdate(nextProps,nextState)

getSnapshotBeforeUpdate(prevProps, prevState)

React 16 版本加入的生命周期
update发生的时候,在render之后,在组件dom渲染之前。
返回一个值,作为componentDidUpdate的第三个参数。

componentDidUpdate(prevProps, prevState)

在组件发生更新之后会被立即调用,但是在初始化的时候不会被调用。
当组件的props或state发生变化时,这个方法也是处理网络请求等操作比较好的地方。

componentDidUpdate(prevProps) {
  // Typical usage (don't forget to compare props):
  if (this.props.userID !== prevProps.userID) {
    this.fetchData(this.props.userID);
  }
}

卸载的方法

componentWillUnmount()

在组件被卸载并且摧毁之前调用。

错误处理的方法

static getDerivedStateFromError(error)

componentDidCatch(error, info)

上一篇下一篇

猜你喜欢

热点阅读