首页 > 解决方案 > 无法访问数组中的数据,name[0] 未定义

问题描述

我正在尝试从调用fetch.

当我打印数据时,例如console.log(data),我得到了我想要的结果。但是,当我尝试打印第一个项目时,例如console.log(data[0]),我看到了undefined

componentDidMount = () => {
  fetch("http://localhost/system_reklamacji/php/pobierz_pliki.php", {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      'klucz_nr': this.state.id,

    })
  }).then(res => this.KonkretnePliki(res.json()));

以及发生错误的函数:

KonkretnePliki(e) {
  let pliki = [];

  (e.then(function(value) {
    value.forEach(element => {
      console.log(element[0]);
      let temp = {
        'nazwa': element[0],
        'sciezka': element[1],
        'typ': element[1].slice(element[1].length - 3, ),
      };
      console.log(pliki[0]); // **shows all the information i want**
      pliki.push(temp);
    })
  }));

  console.log(pliki[0]); // **shows undefined**
  this.setState({
    dane: pliki
  });
}

有什么方法可以让我在forEach循环之外获取所需的数据?

标签: javascriptarraysreactjs

解决方案


推荐阅读