3.3 组件生命周期

优质
小牛编辑
128浏览
2023-12-01

与React 组件一样,Rx组件同样具备以下生命周期

  • 组件加载: componentWillMount
  • 组件加载: componentDidMount
  • 组件更新: componentWillReceiveProps
  • 组件更新: shouldComponentUpdate
  • 组件更新: componentWillUpdate
  • 组件更新: componentDidUpdate
  • 组件卸载: componentWillUnmount rx生命周期
  • 初始化: constructor:构造函数
  • componentWillMount:该函数会在render函数前被执行,且一般只会执行一次。
  • 组件渲染: render
  • componentDidMount:这个方法会在组件加载完毕之后立即执行。在这个时候之后组件已经生成了对应的DOM结构,可以通过this.getDOMNode()来进行访问。如果你想和其他JavaScript框架一起使用,可以在这个方法中执行setTimeout, setInterval或者发送AJAX请求等操作(防止异部操作阻塞UI)。

  • componentWillReceiveProps:在组件接收到一个新的prop(或者更新)时被执行。这个方法在初始化render时不会被调用。如果你需要考虑性能,特别是在有上百个组件时,可以使用shouldComponentUpdate来提升应用速度。

  • shouldComponentUpdate:返回布尔值,决定组件是否更新。默认为true

  • componentWillUpdate:在组件接收到新的props或者state但还没有render时被执行。在初始化时不会被执行。

  • componentDidUpdate:在组件完成更新后立即执行。在初始化时不会被执行。一般会在组件完成更新后被使用。例如清除notification文字等操作。

  • componentWillUnmount:主要用来执行一些必要的清理任务。例如清除setTimeout等函数,或者任意的在componentDidMount创建的DOM元素。

具体的例子如下

import { createElement, Component } from 'weex-rx';
import { mount } from 'nuke-mounter';
import { View, Text, Button} from 'nuke';

class Demo extends Component {
    render() {
        return (
            <View>
                <Button onPress = {this.setNewNumber}>点击增加</Button>
                <Text>{this.state.data}</Text>
            </View>
        );
    }

    constructor(props) {
        super(props);

        this.state = {
            data: 0
        }

        this.setNewNumber = this.setNewNumber.bind(this)
    };

    setNewNumber() {
        this.setState({ data: this.state.data + 1 })
    }

    componentWillMount() {
        console.log('Component WILL MOUNT!')
    }

    componentDidMount() {
        console.log('Component DID MOUNT!')
    }

    componentWillReceiveProps(newProps) {
        console.log('Component WILL RECIEVE PROPS!')
    }

    shouldComponentUpdate(newProps, newState) {
        return true;
    }

    componentWillUpdate(nextProps, nextState) {
        console.log('Component WILL UPDATE!');
    }

    componentDidUpdate(prevProps, prevState) {
        console.log('Component DID UPDATE!')
    }

    componentWillUnmount() {
        console.log('Component WILL UNMOUNT!')
    }

}


mount(<Demo />, 'body');

export default Demo;