简体   繁体   English

React.js JSON数据更新,但状态不会更新,因此UI不会更新

[英]React.js JSON data updates but state doesn't and hence UI doesn't update

I am new to React.js and I love it. 我是React.js的新手,我喜欢它。 However, I am new to data-binding. 但是,我是数据绑定的新手。 So I picked a JSON data endpoint from jsontest.com to see if UI re-renders when the data changes. 因此,我从jsontest.com中选择了一个JSON数据终结点,以查看数据更改时UI是否重新渲染。 But I am confused because it doesn't. 但是我很困惑,因为事实并非如此。

http://www.jsontest.com/#date provides time and date in JSON format which obviously updates every second but my UI is still the same. 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')
);

Now my question is, if I have change the state every second using setInterval whats the point of [data changes -> state updates -> UI re-renders] concept? 现在我的问题是,如果我使用setInterval每秒更改一次状态,那么[数据更改->状态更新-> UI重新渲染]概念的意义是什么? Perhaps I am expecting this work as webSockets so I could be wrong. 也许我期望这项工作可以作为webSockets进行,所以我可能是错的。

Can anyone please explain? 谁能解释一下?

Vinon, in order to establish a "real time" connection with a server, we would need to use a more advanced solution, eg web sockets. Vinon,为了与服务器建立“实时”连接,我们需要使用更高级的解决方案,例如Web套接字。 We can't achieve this with a simple AJAX request which delivers just a one-time data fetch from the server. 我们无法通过简单的AJAX请求来实现此目的,该请求仅提供从服务器一次获取的数据。 What we need is a persistent connection between the client and the server so that both parties can start exchanging data in any direction at any time. 我们需要的是客户端与服务器之间的持久连接 ,以便双方都可以随时随地开始在任何方向上交换数据。

Here you can find a good summary: https://blog.pusher.com/making-reactjs-realtime-with-websockets/ 在这里您可以找到一个很好的摘要: https : //blog.pusher.com/making-reactjs-realtime-with-websockets/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM