多维数组中的Cant调用键(ReactJS)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多维数组中的Cant调用键(ReactJS)相关的知识,希望对你有一定的参考价值。
我正在尝试访问data.address.street,但是当我调用data.address.street时,出现键未定义错误。
当我调用data.id,data.name时,我没有任何问题,但是当尝试访问多维数组(对象)中的数据时,我遇到了错误。
这是我想通过以下方式致电: https://jsonplaceholder.typicode.com/users/1
我得到的错误:
TypeError: Cannot read property 'street' of undefined
这是完整的数据日志:
address:
city: "Gwenborough"
geo: lat: "-37.3159", lng: "81.1496"
street: "Kulas Light"
suite: "Apt. 556"
zipcode: "92998-3874"
__proto__: Object
company:
bs: "harness real-time e-markets"
catchPhrase: "Multi-layered client-server neural-net"
name: "Romaguera-Crona"
__proto__: Object
email: "Sincere@april.biz"
id: 1
name: "Leanne Graham"
phone: "1-770-736-8031 x56442"
username: "Bret"
website: "hildegard.org"
__proto__: Object
我呼叫data.address时记录的内容:
Object
city: "Gwenborough"
geo: lat: "-37.3159", lng: "81.1496"
street: "Kulas Light"
suite: "Apt. 556"
zipcode: "92998-3874"
__proto__: Object
代码:
import React, useState, useEffect from 'react'
export default class UserPage extends React.Component
//https://www.taniarascia.com/using-react-router-spa/
constructor(props)
super(props);
this.state =
data: [],
value: '',
loading: true
;
console.log(this.state)
// Using useEffect to retrieve data from an API (similar to componentDidMount in a class)
useEffect = () =>
// Pass our param (:id) to the API call
fetch("https://jsonplaceholder.typicode.com/users/"+this.props.match.params.id)
.then(response => response.json())
.then(json => this.setState( data: json ))
.then(this.setState(loading: false));
componentDidMount()
this.useEffect();
// Return a table with some data from the API.
render()
const data, value, loading = this.state;
console.log(data.address);
return (
loading ? (
<div>Loading...</div>
) : (
<div className="container">
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Username</th>
<th>Email</th>
<th>Street</th>
<th>Phone</th>
<th>Website</th>
</tr>
</thead>
<tbody>
<tr>
<td>data.id</td>
<td>data.name</td>
<td>data.username</td>
<td>data.email</td>
**<td>data.address.street</td>**
<td>data.phone</td>
<td>data.website</td>
</tr>
</tbody>
</table>
</div>
))
答案
我创建了一个stackblitz来获取用户并显示地址,您可以对此进行交叉验证。
以上是关于多维数组中的Cant调用键(ReactJS)的主要内容,如果未能解决你的问题,请参考以下文章