【问题标题】:why can't i acces elements in an array of JSONs为什么我不能访问 JSON 数组中的元素
【发布时间】:2019-11-28 11:56:15
【问题描述】:

我正在尝试通过对象数组进行映射,每个对象都是从我项目中的 JSON 文件夹中获取的。然后我想将每个对象渲染为一个反应组件。为了实现这一点,我将组件的状态设置为该对象数组。

class List extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: []
    };
  }

当我 console.log() 我的状态似乎是我需要的,但是当我尝试 console.log() 该数组的第一个元素时,它是未定义的。 这是console.log(this.state.data)

[]
0: {description: "AirEuropa Boarding Pass", organizationName: "Air Europa", passTypeIdentifier: "pass.com.globalia.aireuropa.boardingpass", serialNumber: "RB47ZP20082C640001010191641560895200000", teamIdentifier: "ELASV6M68G", …}
1: {formatVersion: 1, passTypeIdentifier: "pass.com.renfe-RenfeTicket", serialNumber: "00HHGV7F7353900982276", teamIdentifier: "H9VY2F2XZA", webServiceURL: "https://www.myserver.com/pathto/service", …}
length: 2
__proto__: Array(0)

为什么 this.state.data[0] 未定义?

这就是我从 JSON 中获取数据的方式

    const arr = [];
    axios
      .get("data")
      .then(res => {
        const arrayDatas = res.data;
        arrayDatas.forEach(element => {
          if (element.includes(".json")) {
            axios.get("data/" + element).then(res => {
              arr.push(res.data);
            });
          }
        });
        this.setState({
          data: arr
        });
      })
      .catch(error => console.error(error));
  }

【问题讨论】:

标签: javascript json reactjs


【解决方案1】:

您应该按照以下建议更新您的状态。

    const arr = [];
    axios
      .get("data")
      .then(res => {
        const arrayDatas = res.data;
        arrayDatas.forEach(element => {
          if (element.includes(".json")) {
            axios.get("data/" + element).then(res => {
              arr.push(res.data);
            });
          }
        });
        this.setState({
           data: arr
         });

      })
      .catch(error => console.error(error));
  }

【讨论】:

    【解决方案2】:
    const arr = [];
        axios
          .get("data")
          .then(res => {
            const arrayDatas = res.data;
            arrayDatas.forEach(element => {
              if (element.includes(".json")) {
                axios.get("data/" + element).then(res => {
                  this.setState({data: res.data});
                });
              }
          })
          .catch(error => console.error(error));
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-13
      • 1970-01-01
      相关资源
      最近更新 更多