json data as react state is not updated

时间:2017-04-06 17:08:59

标签: javascript reactjs

I am learning to develop an app using reactjs in frontend.

I should get a response from a server as json. I am interested in only the particular array object in that json. I need to display the updated data in the browser. It should be updated realtime in the browser. To do this : My understanding is that the resultant json should be a state property in react and whenever it is updated in the server it will be re-rendered in the webpage. I tried the following:

class app extends Component {
   constructor(props){
   super(props);
   this.state = {
   result: [],
   }
   componentDidMount(){
      var that =this;
      axios.get('url').then(function(response){
      for(i=1;i<response.data.result.length;i++)
      {
         var array = that.state.result.slice();
         array.push(response.data.result[i])
         that.setState({
         result: array
      })
      });  
   }
}
render(){
   <div>
     <h1> Result is: {this.state.result}</h1> 
   </div>

This makes the request once to the server and displays the data available at that moment.

  1. When the json is updated in the server due to other actions after the initial get, the real time data is not updated in the browser. Isn't that the purpose of axios.get call? to continuously fetch real time data? Sorry I am so new to frontend.

  2. Is it correct way: that the data fetched from server(array part of json) to directly assign in state using for loop? Or is there a simpler/correct way to assign json directly as state in component?

  3. Why can't I directly use this.setState in componentdidmount() method? Why should I assign "var that"? If I use directly it's throwing error that setstate property cannot read null value , even though it is assigned initial value in constructor?

Thanks.

0 个答案:

没有答案