我正在尝试访问对象中的单个元素,但不断出现错误。
这是我的React组件:
import React, { Component } from "react";
import { fetchCoin } from "../redux/actions";
import { connect } from "react-redux";
class ViewCoin extends Component {
componentDidMount() {
this.props.fetchCoin(this.props.match.params.symbol);
}
render() {
console.log("Props:", this.props.coin);
return (
<div>
<h2>View Item Page</h2>
</div>
);
}
}
const mapStateToProps = state => {
return {
coin: state.coins.coin
};
};
export default connect(mapStateToProps, { fetchCoin })(ViewCoin);
此代码返回以下对象:
{
"BTC": {
"urls": {
"website": [
"https://bitcoin.org/"
],
"twitter": [],
"reddit": [
"https://reddit.com/r/bitcoin"
],
"message_board": [
"https://bitcointalk.org"
],
"announcement": [],
"chat": [],
"explorer": [
"https://blockchain.info/",
"https://live.blockcypher.com/btc/",
"https://blockchair.com/bitcoin/blocks"
],
"source_code": [
"https://github.com/bitcoin/"
]
},
"logo": "https://s2.coinmarketcap.com/static/img/coins/64x64/1.png",
"id": 1,
"name": "Bitcoin",
"symbol": "BTC",
"slug": "bitcoin",
"date_added": "2013-04-28T00:00:00.000Z",
"tags": [
"mineable"
],
"category": "coin"
}
}
例如,当尝试访问硬币名称时,我发出命令:
console.log(this.props.coin.BTC.name);
我收到错误消息:无法读取未定义的属性'BTC'
我测试了在React之外的该对象中访问值的能力,并且能够访问不同的值。如何使用React访问这样的嵌套对象。
谢谢。
答案 0 :(得分:1)
可能发生的是组件第一次渲染coin
时未定义。动作返回时,道具会更新,组件会重新渲染,coin
会退出。
在渲染中执行类似的操作,它应该可以工作:
this.props.coin && console.log('coin name:', this.props.coin.BTC.name)