无法从对象获取数据Uncaught TypeError:无法读取未定义

时间:2017-09-05 13:21:46

标签: javascript json reactjs axios

我有一个像这样的json数据:

"results": [
    {
      "gender": "male",
      "name": {
        "title": "mr",
        "first": "romain",
        "last": "hoogmoed"
      },
      "location": {
        "street": "1861 jan pieterszoon coenstraat",
        "city": "maasdriel",
        "state": "zeeland",
        "postcode": 69217
      },
      "email": "romain.hoogmoed@example.com",
      "login": {
        "username": "lazyduck408",
        "password": "jokers",
        "salt": "UGtRFz4N",
        "md5": "6d83a8c084731ee73eb5f9398b923183",
        "sha1": "cb21097d8c430f2716538e365447910d90476f6e",
        "sha256": "5a9b09c86195b8d8b01ee219d7d9794e2abb6641a2351850c49c309f1fc204a0"
      },
      "dob": "1983-07-14 07:29:45",
      "registered": "2010-09-24 02:10:42",
      "phone": "(656)-976-4980",
      "cell": "(065)-247-9303",
      "id": {
        "name": "BSN",
        "value": "04242023"
      },
      "picture": {
        "large": "https://randomuser.me/api/portraits/men/83.jpg",
        "medium": "https://randomuser.me/api/portraits/med/men/83.jpg",
        "thumbnail": "https://randomuser.me/api/portraits/thumb/men/83.jpg"
      },
      "nat": "NL"
    }
  ],
  "info": {
    "seed": "2da87e9305069f1d",
    "results": 1,
    "page": 1,
    "version": "1.1"
  }
}

我是从Axios获取数据对象的, 当我在console.log(this.state.contact.location)时,它显示了位置对象

{street:“2868 avenidadealalucía”,城市:“gandía”,州:“regióndemurcia”,邮政编码:43796}

但是当我尝试console.log时(this.state.contact.location.street) 我收到错误

未捕获的TypeError:无法读取未定义的属性“street”

这是我的代码:

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
import React, { Component } from 'react';
import AppBar from 'material-ui/AppBar';
import Drawer from 'material-ui/Drawer';
import MenuItem from 'material-ui/MenuItem';
import axios from 'axios';
import {
  Table,
  TableBody,
  TableHeader,
  TableHeaderColumn,
  TableRow,
  TableRowColumn
} from 'material-ui/Table';

export default class App extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
          open: false,
          contact: []
        }
    }

  componentDidMount() {
    axios.get('https://randomuser.me/api/')
      .then((result) => {
          this.setState({
            contact: result.data.results[0]
          })
      })
      .catch(function (error) {
        console.log(error);
      })      
  }  

    handleToggle = () => this.setState({ open: !this.state.open });
    handleClose = () => this.setState({ open: false });
    
    render() {
      console.log(this.state.contact.location)
      //console.log(this.state.contact.location.city) i can't use this
      return (
        <div className="App">
            <AppBar
              title="My App"
              iconClassNameRight="muidocs-icon-navigation-expand-more"
              onLeftIconButtonTouchTap={this.handleToggle}   
            />   
            <Drawer 
              docked={false}
              open={this.state.open}
              onRequestChange={(open) => this.setState({ open })}>
              <MenuItem onClick={this.handleClose}>Contact List</MenuItem>
              <MenuItem onClick={this.handleClose}>To-Do List</MenuItem>
            </Drawer>  
            <Table>
              <TableHeader displaySelectAll={false} adjustForCheckbox={false}>
                <TableRow>
                  <TableHeaderColumn >No</TableHeaderColumn>
                  <TableHeaderColumn >Name</TableHeaderColumn>
                  <TableHeaderColumn >Gender</TableHeaderColumn>
                  <TableHeaderColumn >Email</TableHeaderColumn>
                  <TableHeaderColumn >Phone</TableHeaderColumn>
                </TableRow>
              </TableHeader>
              {/* <TableBody displayRowCheckbox={false}>
                      <TableRow>
                        <TableRowColumn>{1}</TableRowColumn>
                        <TableRowColumn>{this.state.contact.name.first}</TableRowColumn>
                        <TableRowColumn>{this.state.contact.gender}</TableRowColumn>
                        <TableRowColumn>{this.state.contact.email}</TableRowColumn>
                        <TableRowColumn>{this.state.contact.phone}</TableRowColumn>
                      </TableRow>
              </TableBody>      */}
            </Table>
        </div>      
      )    
    }
}

1 个答案:

答案 0 :(得分:0)

你的代码很好。错误的原因是console.log本身。

console.log(this.state.contact.location)
console.log(this.state.contact.location.city)

在第一次装载时,您的state.contact是一个空数组,以便state.contact.location返回undefinedstate.contact.location.city会给您错误。从axios获取数据后,您的数据应该正确