简体   繁体   中英

Unable to access nested object in React

I am trying to access single elements within an object and I keep getting an error.

Here is my React Component:

 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); 

This code returns the following object:

 { "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" } } 

When trying to access the coin name, for example, I issue the command:

console.log(this.props.coin.BTC.name);

I get the error: Cannot read property 'BTC' of undefined

I tested accessing values in this object outside of React and I am able to access the different values. How would one access a nested object like this using React.

Thanks in advance.

What's likely happening is the first time that component renders coin is undefined. When the action returns, the props are updated, the component re-renders and coin is logged out.

Do something like this in render and it should work:

this.props.coin && console.log('coin name:', this.props.coin.BTC.name)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM