【发布时间】:2016-10-01 08:35:49
【问题描述】:
我是 React.js 的新手,我喜欢它。但是,我是数据绑定的新手。因此,我从 jsontest.com 中选择了一个 JSON 数据端点,以查看 UI 是否在数据更改时重新呈现。但我很困惑,因为它没有。
http://www.jsontest.com/#date 提供 JSON 格式的时间和日期,显然每秒更新一次,但我的 UI 仍然相同。
const App = React.createClass({
// Initial time to be empty string
getInitialState: function () {
return {
time: ""
}
},
componentDidMount: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function(data) {
// Setting the state to the response received from JSON endpoint
this.setState({time: data.time});
console.log(this.state);
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
render: function() {
return (
<div>{this.state.time}</div>
);
}
});
ReactDOM.render(
<App url={"http://date.jsontest.com/"} />,
document.getElementById('content')
);
现在我的问题是,如果我每秒都使用 setInterval 更改状态,那么 [数据更改 -> 状态更新 -> UI 重新渲染] 概念的意义何在?也许我期待这项工作是 webSockets,所以我可能是错的。
谁能解释一下?
【问题讨论】:
-
请注意,当您在 ajax 调用中使用
console.log(this.state);时,您将看不到更新状态,原因如下:stackoverflow.com/questions/39804278/… -
我明白了。但是我在这里错过了什么?我需要做什么才能让这个组件获取实时更新?
-
@VinodSobale 尝试登录渲染函数并检查状态是否更新
-
嗯,我看到一个对象正确显示了组件安装的时间。但这是意料之中的
-
我的意思是我可以通过添加一个每秒获取数据并更新状态的函数来很好地做到这一点,但在实际项目中这样做似乎很愚蠢。内存中的这么多间隔会立即使我的应用程序崩溃。
标签: javascript jquery json reactjs data-binding