首页 > 解决方案 > 如何使用点符号访问此对象数组中的嵌套值?

问题描述

import React, { Component } from 'react';
import axios from 'axios';

class Home extends Component {

  state = {
    responses: []
  }

  componentDidMount() {
    this.fetchQuestionAnswers();
  }

  fetchQuestionAnswers = () => {
   if (this.state.activeSupervisionId) {
    axios.get('/question/response/' + this.state.activeSupervisionId).then(res => {
     this.setState({ responses: res.data.data || [] });
     console.log(this.state.responses[0].value)
// dot notation work here inside the function
    }).catch(err => console.error(err));
   }
  }

  render() {
     console.log(this.state.responses[0].value)
// dot notation not working here under render function but the result of // console.log(this.state.responses[0]) is printed
    return (
    )
  }
}
export default Home;

我从作为对象数组发送的 API 中获取数据。所以可以说我设置了responses: res.data.data. 响应控制台的结果如下所述。

var responses = [0: {…}, 1: {…}, 2: {…}, 3: {…}, 4: {…},...]

指数值

我将使用 0 索引对象作为我想要实现的示例。我已经搜索了其他答案,但无法弄清楚。

0: {
  id: 5,
  questionId: 1,
  score: "0",
  text: "Are there any others",
  value: {
    designations: {
      CCO: { no: "3" },
      CDD: { no: "1" },
      DSNO: { no: "1" }
    },
    reaportedStaff: [ "DSNO", "CCO", "CDD" ]
    staffLivingInQuarter: "yes"
    totalReaportedStaff: 5
  }
}

我想知道如何使用点表示法或其他方法(即 id、score、text、CCO 否)访问数组中对象内的属性值?

请注意,我已经尝试过responses[0].value并打印了TypeError: Cannot read properties of undefined (reading 'value')

标签: javascriptreactjs

解决方案


推荐阅读