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!
它運行良好,非常感謝解決方案和解釋! –
很高興聽到它。在開發過程中始終在渲染函數中使用它可能很方便:'console.log('render',this.props,this.state);'這樣你就可以觀察所有更新並查看是否需要優化以減少用'shouldComponentUpdate'函數重新渲染。 – Scott