componentWillUnMount没有为reactjs 0.13调用

时间:2015-03-10 02:24:20

标签: javascript reactjs

代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name=description content="">
    <meta name=viewport content="width=device-width, initial-scale=1">
    <title>Component Lifecycle: Mounting</title>
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.0-beta.1/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.0-beta.1/JSXTransformer.js"></script>
    <style type="text/css">
        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;harmony=true">
    /** @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'};
            }
        },
        render: function() {
            console.log("hello world");
            return <button 
                        style={this.btnStyle}
                        onClick={this.update}>
                        {this.props.val*this.state.m}
                    </button>
        },
        componentDidMount:function(rootNode) {
            this.inc = setInterval(this.update, 500);
        },
        componentWillUnMount:function() {
            console.log("goodbye cruel world!");
            clearInterval(this.inc);
        }
    });
    window.render = function() {
        React.render(
            <APP val={0} />,
            document.getElementById('panel')
        );  
    };

    window.unmount = function() {
        React.unmountComponentAtNode(
            document.getElementById('panel')
        );  
    };

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

我的结果:

enter image description here

正如你所看到的,为了让我能够clearInterval,不知道是不是要调用unmount。其他一切都在起作用。

我哪里出错了?

1 个答案:

答案 0 :(得分:2)

在评论中正式确定Brandon Pugh的答案:

该方法为componentWillUnmount

问题在于大写的M

        ...
    },
    componentWillUnMount:function() { // <- should be componentWillUnmount
        console.log("goodbye cruel world!");
        ...