Ở bài viết này mình sẽ giới thiệu các bạn những callback function được gọi trong xuyên suốt chu trình khởi tạo cho đến hủy 1 component. Mình sử dụng phiên bản mới nhất ở thời điểm viết bài này là 0.13.3

Các callback function liên quan đến việc mouting 1 component, được minh họa ở code dưới này, mình đã giải thích rõ ràng trong các comment code, các bạn chỉ cần copy toàn bộ code dưới đây vào file HTML và mở console lên là có thể thưởng thức.

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Component Lifecycle: Mounting</title>
    <script src="http://fb.me/react-0.13.3.js"></script>
    <script src="http://fb.me/JSXTransformer-0.13.3.js"></script>
    <style>
    body {
        margin: 25px;
    }
    </style>
</head>
<body>
<button onClick="render()">Render</button>
<button onClick="unmount()">Unmount</button>
<hr />
<div id="panel"></div>
<script type="text/jsx">
    /** @jsx React.DOM */
    var APP = 
        React.createClass({
            update:function(){  //Ham update khi click vao button
                var newVal = this.props.val+1
                this.setProps({val:newVal})
            },
            componentWillMount:function(){
                console.log("Truoc khi render HTML") //Xay ra truoc khi render view html 
            },
            render:function(){ //Render Html
                console.log("hello world")
                return <button onClick={this.update}>{this.props.val}</button>
            },
            componentDidMount:function(){  //Xay ra sau khi render view HTML
                console.log("Sau khi render HTML")
            },
            componentWillUnmount:function(){ //Xay ra khi goi len Unmount 
                console.log("Khi bi unmount")
            },
        });

        window.render = function(){
            React.render(
                <APP val={0} />,
                document.getElementById('panel'))   
        }
        window.unmount = function(){
            React.unmountComponentAtNode(document.getElementById('panel'))
        }
</script>
</body>
</html>

Code dưới đây minh họa việc Unmount 1 component, kèm theo việc destroy object javascript được khởi tạo trong quá trình mount (cụ thể ở đây là object interval). Lưu ý thêm, tại sao trong đây mình đặt tên biến là inc, biến này có nghĩa là increment, đặt như vậy cho pro ^^, vì trong MongoDb cũng có thuộc tính $inc, nhiệm vụ là tăng 1 giá trị cho biến số.

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Component Lifecycle: Mounting Uses</title>
    <script src="http://fb.me/react-0.13.3.js"></script>
    <script src="http://fb.me/JSXTransformer-0.13.3.js"></script>
    <style>
    body {
        margin: 25px;
    }
    </style>
</head>
<body>
<button onClick="render()">Render</button>
<button onClick="unmount()">Unmount</button>
<hr />
<div id="panel"></div>
<script type="text/jsx">
    /** @jsx React.DOM */
    var APP = 
        React.createClass({
            update:function(){
                var newVal = this.props.val+1
                this.setProps({val:newVal})
            },
            componentWillMount:function(){
                this.setState({m:2});
                if(this.props.val===0){
                    this.btnStyle = {'color':'red'}  //Dung cho Style color cua button
                }
            },
            render:function(){
                console.log("hello world")
                return  <button
                                    style={this.btnStyle}
                                    onClick={this.update}>
                                    {this.props.val*this.state.m}
                                </button>
            },
            componentDidMount:function(){
                this.inc = setInterval(this.update,500) //Luu object interval vao 1 bien de tien xu ly
            },
            componentWillUnmount:function(){
                console.log("Unmount!")
                clearInterval(this.inc) //destroy bien inc dang chua interval
            },
        });

        window.render = function(){
            React.render(
                <APP val={0} />,
                document.getElementById('panel'))   
        }
        window.unmount = function(){
            React.unmountComponentAtNode(document.getElementById('panel'))
        }
</script>
</body>
</html>

Code dưới đây minh họa việc update state có điều kiện, chỉ khi đúng điều kiện thì mới update state, render lại giao diện

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Component Lifecycle: Updating</title>
     <script src="http://fb.me/react-0.13.3.js"></script>
    <script src="http://fb.me/JSXTransformer-0.13.3.js"></script>
    <style>
    body {
        margin: 25px;
    }
    </style>
</head>
<body>
<div id="panel"></div>
<script type="text/jsx">
    /** @jsx React.DOM */
    var APP = 
        React.createClass({
            getInitialState:function(){
                return {increasing:false} //Khoi tao state. Khi lay this.state.increasing
            },
            update:function(){ //Ham update
                var newVal = this.props.val+1
                this.setProps({val:newVal})
            },
            componentWillReceiveProps:function(nextProps){ //Function nay chay mỗi khi có thay đổi props
                this.setState({increasing:nextProps.val>this.props.val})
            },
            shouldComponentUpdate: function(nextProps, nextState) { //Function này la điều kiện, để có update lai state không
				//chẳng hạn ở đây: chỉ khi nextProps.val chia hết cho 5 thì mới update state
				//Ngoai những trường hợp này ra, khi click button để update thi không có tác dụng gì cả
				//Ở đây bạn có thể bỏ bất kỳ điều kiện gì, miễn sao trả về là TRUE/ FALSE
              return nextProps.val % 5 ===0;
            },
            componentWillUpdate: function(nextProps, nextState) {
				//Hiển thị giá trị trong tương lai của state
              console.log("nextProps ===" + JSON.stringify(nextProps))
            },
            render:function(){
                console.log(this.state.increasing)
                return  (
                                <button
                                    onClick={this.update}>
                                    {this.props.val}
                                </button>
                                )
            },
            componentDidUpdate: function(prevProps, prevState) {
				//prevProps, prevState: lưu lại các giá trị trước khi thay đổi của Props và State
              console.log("prevProps ===" + JSON.stringify(prevProps))
            }
        });


    React.render(
        <APP val={0} />,
        document.getElementById('panel'))   

</script>
</body>
</html>

Các bạn cần lưu ý 2 khái niệm dưới đây để sử dụng cho đúng mục đích.

Props: nhiệm vụ lưu các biến không cần binding lên giao diện.

State: lưu các biến có binding lên giao diện, khi thay đổi trên state thì trên giao diện thay đổi theo.

Lưu ý: mình giải thích toàn bộ code ngay trong source, đôi khi mình sử dụng các từ ngữ rất bình dân, không đúng thuật ngữ, để mọi người có thể dễ hiểu, tiếp thu nhanh chóng.

ReactJS – Component Lifecycle

Category: Uncategorized
0
5708 views

Join the discussion

Your email address will not be published. Required fields are marked *