2017-08-27 59 views
1

我有一個由服務器返回的JSONArray。我想在它上面使用.map(),以便我可以獲取該數組中存在的每個對象的鍵,值對。我寫了下面的代碼,但我收到錯誤「files.map不是一個函數」。任何人都可以幫我解決這個問題嗎?如何在reactjs中對JSONArray使用.map()函數ES6

showUploadedFiles() 
    { 
    const page = 1; 
    const items_per_page = this.state.event.file_ids.length; 
    getAllTaskFiles(this.state.event.id, page, items_per_page).then((allFiles) => { 
     this.renderUploadedFiles(allFiles); 
    }); 

    } 

    renderUploadedFiles(files) 
    { 
    let details = null; 
    details = files.map((singleFile) => { 
    return (
     <div> 
     <a href="#" >{singleFile.filename}</a> 
     <a href="#" >{singleFile.file_path}</a> 
     </div> 
    ); 
    }); 
    } 

我JSONArray是:

[{"file_id": 5224879255191552, "filename": "children_walk_friends_forest_116878_3840x2160.jpg", "file_path": "/api/files/encoded_gs_file%3AdHJhY2tpbmctYXBpL3YxL2FjY291bnRzLzU2Mjk0OTk1MzQyMTMxMjAvdGFza3MvNDk5NjE4MDgzNjYxNDE0NC81MjI0ODc5MjU1MTkxNTUyL2Zha2UtemRNeklhZ1RTYl9PN3RXY2pXbkhVQT09"}, {"file_id": 4943404278480896, "filename": "banner_old.jpg", "file_path": "/api/files/encoded_gs_file%3AdHJhY2tpbmctYXBpL3YxL2FjY291bnRzLzU2Mjk0OTk1MzQyMTMxMjAvdGFza3MvNDk5NjE4MDgzNjYxNDE0NC80OTQzNDA0Mjc4NDgwODk2L2Zha2UtcmJjbDBVdVFzVmZkMjRtRUV2ME1xZz09"}] 
+5

你肯定'allFiles'或'files'是真正的陣列? '.map()'之前是否嘗試過'console.log()'? – Nocebo

+0

@Nocebo是的,我發佈的JSONArray實際上是console.log給我的。 – HamidArrivy

+2

現在嘗試'console.log(typeof文件)',看看它說什麼 – adeneo

回答

2

正如其他用戶所指出的,你必須使用JSON.parse()從您的字符串獲取對象。這裏是代碼片段,將你的文件存儲在一個數組中。

var str = '[{"file_id": 5224879255191552, "filename": "children_walk_friends_forest_116878_3840x2160.jpg", "file_path": "/api/files/encoded_gs_file%3AdHJhY2tpbmctYXBpL3YxL2FjY291bnRzLzU2Mjk0OTk1MzQyMTMxMjAvdGFza3MvNDk5NjE4MDgzNjYxNDE0NC81MjI0ODc5MjU1MTkxNTUyL2Zha2UtemRNeklhZ1RTYl9PN3RXY2pXbkhVQT09"}, {"file_id": 4943404278480896, "filename": "banner_old.jpg", "file_path": "/api/files/encoded_gs_file%3AdHJhY2tpbmctYXBpL3YxL2FjY291bnRzLzU2Mjk0OTk1MzQyMTMxMjAvdGFza3MvNDk5NjE4MDgzNjYxNDE0NC80OTQzNDA0Mjc4NDgwODk2L2Zha2UtcmJjbDBVdVFzVmZkMjRtRUV2ME1xZz09"}]'; 
 

 
var files = JSON.parse(str); 
 

 
var details = files.map((singleFile) => { 
 
return (
 
    <div> 
 
    <a href="#" >{ singleFile.filename}</a> 
 
    <a href="#" >{singleFile.file_path}</a> 
 
    </div> 
 
); 
 
}); 
 

 
console.log(details);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

相關問題