如果你熟悉avalon,使用过 data-include-rendered 和 data-include-loaded 等回调方法,那么你会很好地理解React组件的各个生命周期。

说白了其实就是React组件状态变化前后的时间点,我们可以利用生命周期的接口在相应的时间点做回调操作。

React的官方文档提及了如下几个组件的生命周期:

Mounting/组件挂载相关: 

componentWillMount
componentDidMount

Updating/组件更新相关:

componentWillReceiveProps
shouldComponentUpdate
componentWillUpdate
componentDidUpdate

Unmounting/组件移除相关:

componentWillUnmount 
 

下面我们将通过一些实例来理解它们。顺便说下本文的示例都可以在我的github上下载到。

ReactJS入门(二)—— 组件的生命周期

一. Mounting/组件挂载相关

componentWillMount

在组件挂载之前执行操作,但仅执行一次,即使多次重复渲染该组件,或者改变了组件的state:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>componentWillMount</title>
    <script src="react.js"></script>
    <script src="JSXTransformer.js"></script>
</head>
<body>
<div id="a">123</div>
<script type="text/jsx">
    var i = 0;
    var Component1 = React.createClass({
        componentWillMount: function(){
            console.log(i++)
        },
        getInitialState: function() {
            return {
                isClick: !1
            }
        },
        clickCb: function() {
            this.setState({
                isClick : !0
            })
        },
        render: function() {
            return <div onClick={this.clickCb}>isClick:{this.state.isClick? 'yes' : 'nope'}</div>
        }
    });
    var div = document.getElementById('a');
    React.render(
        <Component1 />,div
    );
    React.render(
        <Component1 />,div
    );
</script>
</body>
</html>

ReactJS入门(二)—— 组件的生命周期

如果希望该回调能执行多次,可以使用 React.unmountComponentAtNode(该方法我们下篇文章再介绍)移除掉已有的组件,然后再重新 render:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>componentWillMount</title>
    <script src="react.js"></script>
    <script src="JSXTransformer.js"></script>
</head>
<body>
<div id="a">123</div>
<script type="text/jsx">
    var i = 0;
    var Component1 = React.createClass({
        componentWillMount: function(){
            console.log(i++)
        },
        getInitialState: function() {
            return {
                isClick: !1
            }
        },
        clickCb: function() {
            this.setState({
                isClick : !0
            })
        },
        render: function() {
            return <div onClick={this.clickCb}>isClick:{this.state.isClick? 'yes' : 'nope'}</div>
        }
    });
    var div = document.getElementById('a');
    React.render(
        <Component1 />,div
    );
    React.unmountComponentAtNode(div);  //移除掉已有组件
    React.render(
        <Component1 />,div
    );
</script>
</body>
</html>
View Code

相关文章:

  • 2018-04-09
  • 2022-03-06
  • 2022-12-23
  • 2022-12-23
  • 2022-01-14
猜你喜欢
  • 2022-01-11
  • 2022-12-23
  • 2021-11-28
  • 2021-10-30
  • 2022-12-23
  • 2021-09-09
相关资源
相似解决方案