天天看點

react-state的問題

react-state的問題

1、setState是異步的,在調用了setState之後,this.state的值并沒有立即改變,可能還是使用原來的值。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>測試state</title>
    <script type="text/javascript" src="bower_components/react/react.js"></script>
    <script type="text/javascript" src="bower_components/react/JSXTransformer.js"></script>
</head>
<body>

    <div id="app"></div>
    <!-- 遺留問題!!! -->
    <script type="text/jsx">
        var MessageBox = React.createClass({
            handleClick:function(){
                this.setState({
                    clickCount: this.state.clickCount + ,
                    clickContent: '你一共點選了'+this.state.clickCount+'次'
                });
            },
            getInitialState: function(){
                return {
                    clickCount: ,
                    clickContent: '你還沒有點選哦'
                }
            },
            render: function(){
                return (
                    <div>
                        <h3>點選下面按鈕:</h3>
                        <button onClick={this.handleClick}>點選我</button>

                        <div>{this.state.clickContent}</div>
                    </div>
                );
            }
        });

        React.render(
            <MessageBox />,
            document.getElementById('app')
        );
    </script>
</body>
</html>