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