Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

javascript - get value of #text from object react

Im using Last.fm API for get artist info.

I got JSON object format just like this:

object format

how can I access the "#text" with react object, because it getting error when i put # sign.

import React, { Component } from 'react';
import './App.css';


class Profile extends Component{
    render(){
        let artist = {name:'', stats:{listeners:''},bio:{published:''}, image:[{#text:''}]};

        artist = this.props.artist !== null ? this.props.artist : artist;

        return(
            <div>
                <img
                    alt="Profile"
                    className="profile-img"
                    src={artist.image[0].#text}
                />
                <div>{artist.name}</div>
                <div>{artist.stats.listeners}</div>
                <div>{artist.bio.published}</div>
            </div>
        )

    }
}

export default Profile;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Fortunately in javascript, we can access object properties in 2 ways. We can do it using the 'dot' like you have, but this doesn't work in a couple of scenarios such as when the property has a space, is a key word or the scenario that you're experiencing above.

The other method, is to put the property inside of square brackets. In your case, you could do artist.image[0]["#text"]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...