2017-06-18 134 views
-2

我已經設置了名爲data的狀態並將其聲明爲getInitialState()中的空數組。此外,我已經做了一個Ajax調用,並獲得了componentDidMount()中返回的JSON。如何使用React中的setState將多個JSON請求推送到數組中

如何使用setState方法將多個JSON請求推送到稱爲數據的數據?

var Forecast = React.createClass({ 

    getInitialState() { 
     return { 
      data: [] 
     } 
    }, 

    componentDidMount: function() { 
     this.serverRequest = $.get('http://api.openweathermap.org/data/2.5/weather?zip=3000,au&appid=005fa98ae858a29acf836ecdefac0411', function(result) { 
      var tempData = result; 
      this.setState({ 
       // Is there any way to push multiple JSON into an array? 
       // below line of code is my attempt 
       data: tempData 
      }); 
     }.bind(this)); 
    } 

    ... 
} 
+0

'data [0]'是未定義的,因爲數組是空的。不知道ajax調用,你確定結果是一個數組嗎? – webdeb

回答

1

我敢肯定的jQuery不會自動轉換爲數組爲您提供:

this.serverRequest = $.get('http://api.openweathermap.org/data/2.5/weather?zip=3000,au&appid=005fa98ae858a29acf836ecdefac0411', function(result) { 
    var tempData = JSON.parse(result); 
    this.setState({ 
     data: tempData // reset the data 
    }); 
}.bind(this)); 

東西之類的將工作

編輯:您沒有按照協議的API。我手動鍵入它到瀏覽器中,並得到了這樣的結果:

{"coord":{"lon":144.96,"lat":-37.81},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04n"}],"base":"stations","main":{"temp":283.48,"pressure":1032,"humidity":76,"temp_min":282.15,"temp_max":285.15},"visibility":10000,"wind":{"speed":4.6,"deg":360},"clouds":{"all":75},"dt":1497828600,"sys":{"type":1,"id":8201,"message":0.0048,"country":"AU","sunrise":1497821707,"sunset":1497856068},"id":0,"name":"Melbourne","cod":200} 

這顯然不是一個數組(所以你不能說data[0]

如果您要訪問的JSON對象只是去,如:

console.log(data["coord"]); // this will return {"lon":144.96,"lat":-37.81}

編輯:如果你想存儲請求的列表,你需要這樣做:

this.setState({ 
    data: this.state.data.concat(tempData) 
}) 
+0

謝謝,我編輯了我的代碼,以便狀態可以容納一個對象。有沒有辦法使用setState()將對象推入數組?我想保持狀態爲一個數組。 – Hooey

+0

@霍伊好吧,我明白你的意思了。請加上這個問題 – AJC

+0

謝謝。我剛剛加入我的問題 – Hooey

0

看來你是從'api.openweathermap.org'獲得的響應作爲普通的JavaScript對象而不是數組。所以你必須相應地改變你的初始狀態和console.logrender方法。

getInitialState() { 
    return { 
     data: null 
    } 
} 

render() { 
    console.log(this.state.data); 
    //... 
}) 

如果你想要把你的迴應到data數組中的狀態,使用concat

this.setState({ 
    data: this.state.data.concat([tempData]) 
}); 
0

所以,你想把返回的對象放入數組中,添加它?

這個怎麼樣:

... 
this.setState({ 
    data: this.state.data.concat(tempData) 
}); 

你也可以把它推到state.data陣,但後來多了一個步驟是必需的:

this.state.data.push(tempData); 
this.setState({ 
    data: this.state.data 
}); 

而且這將意味着,修改狀態,這不是一個好的做法。對於這個例子,它可能沒問題,但這不是一個好習慣。

+0

是的。它不是一個數組,而是一個json對象。我有一個狀態是一個數組。我的目標是在我的代碼中使用上面定義的setState()將對象放入數組中。 – Hooey

+0

aaa,請參閱我的編輯@Hooey – webdeb

相關問題