2017-11-25 106 views
3

我遇到了React問題。 我有一個數組,我傳遞給this.state。但是我面臨一個問題,我無法訪問數組中的子元素。在我的情況下,我無法訪問this.state.folders [0]。反應this.state undefined數組

這裏是我的代碼:提前

// console.log(this.state.folders); 
     [] 
    0: "Commun" 
    1: "Privé" 
    2: "Public" 
    length: 3 

//console.log(this.state.folders[0]); 
    undefined 

感謝:

class DriveContent extends Component { 
    constructor() { 
     super(); 
     let list_files = []; 
     let list_folders = []; 
     axios.get('/api/getFilesAndFolders').then((response) => { 
      for (var i = 0; i < response.data.length; i++) { 
       if (response.data[i]["isFile"] ==true){ 
        list_files.push(response.data[i]); 
       } 
       else { 
        list_folders.push(response.data[i]); 
       } 
      } 
     }).catch((error) => { 
      console.error(error); 
     }); 

     this.state = {files: list_files, folders: list_folders}; 
     console.log(this.state.folders); 
     console.log(this.state.folders[0]); 
    } 

這裏就是退還2的console.log!

回答

3

您正在設置狀態過快。在回調函數中,在分配給list_fileslist_folders後需要setState,因爲在構造函數完成後執行回調。試試這個:

for (var i = 0; i < response.data.length; i++) { 
    if (response.data[i]["isFile"] ==true){ 
     list_files.push(response.data[i]); 
    } 
    else { 
     list_folders.push(response.data[i]); 
    } 
} 
// setState here: 
this.setState = {files: list_files, folders: list_folders}; 

然後移動你的console.logs到你的渲染函數來查看正在更新的狀態。一旦進行初始構建並在setState之後再次進行。

+1

它運行良好,非常感謝解決方案和解釋! –

+0

很高興聽到它。在開發過程中始終在渲染函數中使用它可能很方便:'console.log('render',this.props,this.state);'這樣你就可以觀察所有更新並查看是否需要優化以減少用'shouldComponentUpdate'函數重新渲染。 – Scott