ReactJs - getInitialState不起作用

问题描述 投票:0回答:1

我正在玩ReactJs,我有这个简单的代码

var User = React.createClass({
    render: function () {
        return(
            <li>
                {this.props.email}
            </li>
        );
     }
});

var UserList = React.createClass({
    reload: function () {
        var xhr = new XMLHttpRequest();
        xhr.open('get', "http://localhost:64501/Home/GetUsers", true);
        xhr.onload = function () {
            var result = JSON.parse(xhr.responseText);
            this.setState({ data: result });
            console.log(JSON.stringify(result));
        }.bind(this);

        xhr.send();
    },

    getInitialState: function () {
        return {
            data: [
                { email: "[email protected]", id: "1" },
                { email: "[email protected]", id: "2" }
            ]
        };
    },

    componentDidMount: function () {
        window.setInterval(this.reload, 3000);  
    },

    render: function () {       
        if (this.props.data != null) {
            var userNodes = this.props.data.map(function (user) {               
                return (
                    <User email={user.email} key={user.id } ></User>
                );
            });

            return (
                <div>
                    <ul>{userNodes}</ul>                    
                 </div>
            );
        }
        else {
            console.log("this.props.data is null");
            return null;
        }        
    }
});

ReactDOM.render(<UserList />, document.getElementById('root'));

我有两个问题: 1 - getInitialState函数返回的数据不由组件呈现。 2 - setState不刷新重载函数中的组件。

javascript reactjs
1个回答
0
投票

你正在读this.props.data,你应该读this.state.data

请注意外部组件属性与组件内部状态之间的差异。

只需用this.props.data替换所有this.state.data,你的代码就可以了。

© www.soinside.com 2019 - 2024. All rights reserved.