2017-05-31 13 views
-1

我正在學習ReactJS以製作一個需要Jquery從服務器提取遠程JSON數據的Web應用程序。當我嘗試手動將JSON數據放入App.js時,該Web應用程序正常工作,但在嘗試提取遠程JSON數據時發生錯誤無法讀取屬性「polls」Null。在Reactjs構造函數中使用Jquery提取JSON數據時,無法讀取Null屬性

這裏是app.js與手動放在JSON數據:

import React, { Component } from 'react'; 
import Polls from './Components/Polls'; 
import './App.css'; 
import $ from 'jquery'; 

class App extends Component { 

    constructor(){ 
    super(); 
     this.state = { 
      polls: [ 
      { 
       survey_id: 1, 
       choice1_votes: 4, 
       choice1_text: "Kanye", 
       choice1_image:"https://a.web.site/kanye.jpg", 
       choice2_votes: 5, 
       choice2_text:"Eminem", 
       choice2_image:"https://a.web.site/eminem.jpg" 
      }, 
      { 
       survey_id: 2, 
       choice1_votes: 7, 
       choice1_text: "Football", 
       choice1_image:"https://a.web.site/football.jpg", 
       choice2_votes: 2, 
       choice2_text: "Soccer", 
       choice2_image:"https://a.web.site/soccer.jpg" 
      } 
     ] 
}; 
     console.log(this.state); 
    } 

    render() { 
    return (
     <div className="App"> 
     My App 
     <Polls polls={this.state.polls}/> 
     </div> 
    ); 
    } 
} 

export default App; 

當我嘗試改變this.state使用jQuery獲得提取的數據...

constructor(){ 
    super(); 
    $.getJSON('sample.json', function (data) { 
     this.state = {data}; 
    }); 
    } 

...我收到一個錯誤無法讀取屬性'民意調查'的空。

如何解決此錯誤?

回答

2

您構建代碼的方式是不正確的,寫這樣的:

首先定義state(初始值)投票變量:

constructor(){ 
    super(); 
    this.state = { 
     polls: [] 
    } 
} 

裝入JSON在componentDidMount生命週期的方法,並使用setState更新state值:

componentDidMount(){ 
    $.ajax({ 
     url: url, 
     dataType: 'json', 
     success: (data) => { 
      this.setState({data: polls}); 
     }, 
     error: (xhr, status, err) => { 
      console.error('error'); 
     } 
    }); 
} 

注意:使用arrow function來綁定正確的上下文。

更新:

你寫的,只有當你加載本地JSON的工作方式,你需要使用fetchaxios或jQuery的Ajax調用進行GET調用從遠程服務器JSON。

+0

它不會出現componentDidMount()曾運行。我剩下一個對象:{polls:[null]}。我應該把它稱爲什麼地方? – Ethernetz

+0

不,你不需要調用,在內部執行'console.log('called')',一旦組件第一次呈現就會被調用。 –

+0

請提供downvote的原因。 –

0

你的問題似乎是一個異步問題。 $.getJSON()我認爲這是一個異步函數,因此它不會停止執行。當你到達構造函數中被調用的那一行時,程序開始執行$.getJSON(),但由於該函數有空閒時間,所以繼續執行constructor()。這意味着constructor()可能在$.getJSON()之前完成執行,因此render()函數會嘗試開始執行並嘗試在爲其設置值之前引用this.state.polls

如果按照Mayank舒克拉的答案,你應該能夠避免這個問題,因爲在構造你定義this.state.polls爲空數組(不是null或undefined)

相關問題