我有下面的數據集Json文件。React + Redux - Reducer子狀態不是一個對象?
在ajax檢索json文件時,我調用了下面的reducer。
export default function clientProfile(state={}, action) {
switch(action.type) {
case GET_CLIENT_SUCCESS:
return action.payload;
default:
return state;
}
}
我想用反向()和.MAP上this.state.client.notes但我不斷收到未定義或爲空的錯誤。轉出時,我這樣做...
console.log(typeof this.state.client); //returns object
console.log(typeof this.state.client.notes); //returns undefined
我確保我返回的JSON文件格式是否正確(希望),但我不明白爲什麼嵌套的狀態不是對象,但未定義。 無論如何解決這個問題,我可以使用.reverse()和.map函數,或者這是按照預期工作?如果它正在工作,那麼除了創建單獨的減速器之外,還有其他選擇。我希望筆記處於客戶端狀態。
{
"customerId": "34",
"agentId": "1",
"createdDate": "1510223892",
"firstname": "John",
"lastname": "Doe",
"mobile": "123456789",
"address": "Something email here",
"notes": {
"0": {
"noteId": "1",
"customerId": "34",
"createdBy": "1",
"created": "1510316194",
"note": "add something"
},
"1": {
"noteId": "2",
"customerId": "34",
"createdBy": "1",
"created": "1510316527",
"note": "add something"
},
"2": {
"noteId": "3",
"customerId": "34",
"createdBy": "1",
"created": "1510317177",
"note": "add new thing"
},
"3": {
"noteId": "4",
"customerId": "34",
"createdBy": "1",
"created": "1510318448",
"note": "something"
},
"4": {
"noteId": "5",
"customerId": "34",
"createdBy": "1",
"created": "1510318476",
"note": "this would be note number 5, lets see whether we can get something from this."
}
}
}
謝謝你搞清楚,如果我把CONSOLE.LOG在渲染()我沒有得到它返回的對象。我被卡住,因爲我也referre這個鏈接
map function for objects (instead of arrays)
所以我有以下代碼內幕渲染()
//$.map(this.props.client.notes, function(note, key) { //This works, but i cannot use reverse()
//Object.keys(this.props.client.notes).map(function(key, note) { //this doesn't work and return error
Object.keys(this.props.client.notes).map(function(key, index) {
return (
<li key={key}>
<div>Key: {key} | Note_id: {this.props.client.notes[index].noteId} AND Note_content: {this.props.client.notes[index].note}</div>
</li>
);
現在我們知道它是一個對象,但上面的代碼仍然不起作用。 如果我能弄清楚客戶端狀態的數據類型,那麼我可以知道該怎麼做。
的平均時間,該aboves返回以下錯誤 ×
TypeError: Cannot convert undefined or null to object
更新:與條件 按照下面我更新了我的代碼,創建printNote(函數的答案),並把{this.printNote代碼}裏面渲染。
我可以看到所有按鍵的控制檯日誌,但是,它沒有在屏幕上呈現。
printNote() {
console.log(this.props);
console.log(this.props.client.notes);
let notes = this.props.client.notes;
console.log('notes',notes);
if(notes) {
console.log('in if ');
Object.keys(notes).map(function(key, index) {
console.log(key);
return (
<li key={key}>
<div>Key: {key} | Note_id: {notes[index].noteId} AND Note_content: {notes[index].note}</div>
</li>
);
})
}
}
首先你不能使用'.map'上'notes'爲它不是'數組',而是'對象'。 「clent」鍵從哪裏來?我沒有在你的json文件中看到它,這是'reducer'的名字嗎? –
是的,它是減速機。對不起,我需要你的幫助了。這是我需要將所有事情都做好的最初階段。 –
顯示代碼,你嘗試用這行'console.log(typeof this.state.client.notes)'輸入'notes';'我打賭你在獲取完成之前嘗試訪問它,狀態(這是一個空對象) –