react.js如何知道数据发生了变化?



使用React.js我写了一个简单的应用程序,获取json并使用返回的一些数据来构建html。

虽然,当JSON改变时,html不会改变。我遗漏了什么吗?

这是我的代码-

<script type="text/jsx">
var classNames = ({
    'auditNumber': "auditNumber",
    'audit-overview-box': "audit-overview-box"
});
var AuditOverviewBox = React.createClass({
    render: function () {
        return (
            <div className="audit-overview-box">
                <h1 className={classNames.auditNumber}>{this.props.auditNo}</h1>
                <span>{this.props.creationDate}</span>
            </div>
        )
    }
});

var AuditBoxes = React.createClass({
    getInitialState: function () {
        return {
            data: []
        }
    },
    componentWillMount: function () {
        this.dataSource();
    },
    componentWillReceiveProps: function (nextProps) {
        this.state.data(nextProps);
    },
    dataSource: function (props) {
        props = props || this.props;
        return $.ajax({
            url: '../json.php',
            dataType: 'json',
            cache: false,
            success: function (data) {
                this.setState({data: data});
            }.bind(this),
            error: function (xhr, status, err) {
                console.error(this.props.url, status, err.toString());
            }.bind(this)
        });
    },

    render: function () {
        var data = this.state.data;
        console.log("data");

        var photos = data.map(function (audit) {
            return <AuditOverviewBox key={audit.auditNo.toString()} auditNo={audit.auditNo}
                                     creationDate={audit.creationDate}/>
        });
        return (
            <div className='myAudits'>
                {photos}
            </div>
        )
    }
});
ReactDOM.render(<AuditBoxes />, document.getElementById('audits-div'));
</script>

和JSON -

[{
    "auditNo": "a1201",
    "creationDate": "21/10/2016"
},
{
    "auditNo": "a1221",
    "creationDate": "21/10/2016"
},
{
    "auditNo": "a1211",
    "creationDate": "21/10/2016"
}]

你不能将更改从服务器推送到浏览器(除非你使用websockets)。如果您只需要在一段时间内更新一次,那么您应该围绕ajax请求设置代码,使其每n秒执行一次请求。最简单的解决方案是使用setInterval()

setInterval(
  function () {
    // your ajax code
  },
  5000
)

,这样对服务器的请求将每5秒完成一次。请注意,如果您将间隔设置为短/有很多访问者,则可能会使服务器过载。

只有两种方法可以更改数据。你可以使用。setstate方法或直接将数据设置为。state属性并调用组件的。forceupdate方法,但这种方法是严格不推荐的。您可以在这里阅读更多信息:https://facebook.github.io/react/docs/state-and-lifecycle.html

相关内容

最新更新