React中JSON内的嵌套对象

时间:2019-11-24 09:46:34

标签: json reactjs

对不起,我是新来的。 我在ASP .Net Core中生成了Data对象,它可以通过GET GetData获得:

using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace ReactImport.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class GetPostExampleController : ControllerBase
    {
        private Data data;

        public GetPostExampleController() =>
            data = new Data();

        [HttpGet("GetData")]
        public Data GetData()
        {
            return data;
        }
    }

    [JsonObject]
    public class Data
    {
        public Data() =>
            NestedData = new NestedData();
        public int Value { get; set; } = 999;
        public NestedData NestedData {get; set;}
    }

    [JsonObject]
    public class NestedData
    {
        public int NestedValue { get; set; } = 888;
    }
}

我可以在我的React应用程序中接收该对象并读取Data.Value,但是如果尝试读取Data.NestedData.NestedValue,则会出现错误TypeError: Cannot read property 'nestedValue' of undefined

import React, { Component } from 'react';

export class GetPostExample extends Component {
    static displayName = GetPostExample.name;

    componentDidMount() {
        this.ReadData();
    }

    constructor(props) {
        super(props);
        this.state = { ReadData: Object, loading: true };
    }

    async ReadData() {
        const response = await fetch('api/GetPostExample/getData');
        const data = await response.json();
        this.setState({ ReadData: data, loading: false });
    }

    render() {
        return (
            <div>
                <div>Get:</div>
                <div>Data.Value = {this.state.ReadData.value}</div>
                {/*TypeError: Cannot read property 'nestedValue' of undefined
                *<div>Data.Value = {this.state.ReadData.nestedData.nestedValue}</div>*/}
            </div>
        );
    }
}

received object

2 个答案:

答案 0 :(得分:0)

如果它是有效的JavaScript Object,则可以这样访问它:

this.state.ReadData.nestedData.nestedValue
const obj = {
  nestedData: {
    nestedValue: 888
  },
  value: 999,
  loading: false
};

class App extends React.Component {
  state = {
    ReadData: obj
  };

  render() {
    return (
      <div>
        <div>Get:</div>
        <div>Data.Value = {this.state.ReadData.value}</div>
        <div>
          Data.NestedData.NestedValue = {this.state.ReadData.nestedData.nestedValue}
        </div>
      </div>
    );
  }
}

Edit Q-59016408-NestedObject

答案 1 :(得分:0)

我找到了答案here

render() {
    let nestedValue;
    if (this.state.ReadData.nestedData && this.state.ReadData.nestedData.nestedValue)
        nestedValue = this.state.ReadData.nestedData.nestedValue;
    return (
        <div>
            <div>Get:</div>
            <div>Data.Value = {this.state.ReadData.value}</div>
            <div>Data.NestedData.NestedValue = {nestedValue}</div>
        </div>
    );
}