reactjs - 如何修复:无法读取未定义的属性“总计”
问题描述
我正在尝试从道具中将对象渲染到我的组件。但是,我已经能够使用 {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>
解决方案
尝试这个:
artist.followers && artist.followers.total
推荐阅读
- macos - MacOS 10.15 (Catalina) 中的 ASWebAuthenticationSession
- gitlab - gitlab中的快进合并请求
- r - 如何动态添加列对
- macos - 如何在 Mac OS 上检查 CPI(每指令周期数)或 IPC(每周期指令数)?
- django - 无法使用 CentOS 8、Nginx 和 Django-Rest-Framework 在 VirtualBox 上启动 gunicorn.service
- asp.net-mvc - 如何诊断 asp.net mvc 中的 ScriptBundle 错误
- javascript - 使用返回的 JSON 数据更改状态
- java - 如何仅更新可能已经为空的某些字段(使用 JSON 补丁)
- python-3.x - 如何使用 av.open() 访问我的网络摄像头麦克风中的音频流?
- python - Pandas 使用第一个有效索引按组删除 nan