2017-08-02 22 views
0

我正在從API中獲取數據,我正在使用React和Redux來這樣做。我正在成功從API獲取數據。 下面是與輸出的console.log:來自API的數據未被輸出| React,Redux

console.log(this.props.customer.data) enter image description here

但我不能讓它在我的陣營應用中展示。我敢打賭,我的問題是非常基本的,但我真的不明白爲什麼這不起作用。

我試着這樣做裏面return

{this.props.customer.data.map(customers => <p>{customers.name}</p>)} 

但我只發現了錯誤:TypeError: Cannot read property 'map' of undefined

如果有人知道爲什麼會發生這種情況,請讓我知道!謝謝!

(我知道我不應該有我的道具奇異的,因爲它代表多個客戶..)

+0

第一次嘗試渲染時失敗嗎?你有'this.props.customer.data'的默認值嗎? –

+0

默認值是什麼意思? –

+0

我的意思是'customer.data'的初始狀態應該是一個數組。 –

回答

3

問題是您沒有customer.data的初始值。

export function customer(state = [], action) { 
    ... 
} 

被設置customer到一個數組:你在另一個評論,你減速是設置這樣提到。相反,請在縮減器中執行類似操作:

const initialState = { 
    data: [] // <-- Default value for customer.data is an empty array 
}; 

export function customer(state = initialState, action) { 
    ... 
} 
+0

有趣的部分是我之前有過,但因爲某些原因我刪除了它.............謝謝邁克! –

+1

@MartinNordström很高興能幫到你! :) –

2

如果從獲取數據的API,你在最初的渲染沒有數據,所以你應該嘗試類似這個:

{this.props.customer.data ? this.props.customer.data.map(customers => 
     <p> 
     {customers.name} 
     </p>) : null} 
3

你基本上是試圖迭代undefined/null對象。好的做法是將redux存儲中的數組初始狀態設置爲空數組。有了這些,你不必在你的組件中添加額外的檢查來檢查數組是否真的存在。 Array.prototype.map只是不會遍歷一個空的數組,並不會呈現任何東西。確保將customer.data的初始狀態設置爲減速器中的空數組。

+0

我在減速機中有這個:export function customer(state = [],action)' –

+0

你能在減速機中顯示整個邏輯嗎? – lukaleli