首页 > 解决方案 > 如何修复:无法读取未定义的属性“总计”

问题描述

我正在尝试从道具中将对象渲染到我的组件。但是,我已经能够使用 {artist.name} 和 {artist.genre) 成功地做到这一点。{artist.followers.total} 失败并出现错误 - 无法读取未定义的属性总数

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

class Profile extends Component {
    render() {
        // console.log('props from profile.jsx', this.props)
        // let artist = {name:'', followers: {href: '', total: ''}}
        let artist = this.state
        if (this.props.artist !== null) {
            artist = this.props.artist;


        };
        return ( <
            div >
            <
            div > {
                artist.name
            } /* works properly returns artist name name: "Kanye West" */ <
            /div> {
                artist.genres
            } /* works properly returns genres: (4) ["chicago rap", "hip hop", "pop rap", "rap"]*/

            <
            div > {
                artist.followers.total
            }
            /*causes run time error, I expect to see the total number of followers as received from the spotify API ollowers:
href: null
total: 10421208  Returns Cannot read property 'total' of undefined*/


            <
            /div>


            <
            /div>


        )



    }




}
export default Profile;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

标签: reactjsjsx

解决方案


尝试这个:

artist.followers && artist.followers.total

推荐阅读