[英]React: OnClick Cannot Set Property 'length' Of Undefined Error React
In the following code, I click on the notification icon and it calls the toggleNotificationMenu function so the viewNotifications action can fire off.在以下代码中,我单击通知图标并调用 toggleNotificationMenu function 以便 viewNotifications 操作可以触发。 However, when I do that I get the following error: "cannot read property 'length' of undefined" which is regarding the newNotifications.
但是,当我这样做时,我收到以下错误:“无法读取未定义的属性'长度'”,这与 newNotifications 有关。 However, when I console.log newNotifications I can see it successfully displays an array with objects in it.
但是,当我 console.log newNotifications 我可以看到它成功显示了一个包含对象的数组。 viewNotifications action does successfully fire because I can see the changes made in my database.
viewNotifications 操作确实成功触发,因为我可以看到在我的数据库中所做的更改。 I just cannot figure out why I am getting the error.
我只是无法弄清楚为什么我会收到错误消息。
class TopNavbar extends Component{
static propTypes = {
newNotifications: PropTypes.object,
viewNotifications: PropTypes.func.isRequired
};
toggleNotificationMenu = () =>{
const {newNotifications} = this.props.notifications;
console.log(newNotifications)
if(newNotifications.length > 0){
this.props.viewNotifications()
}
}
render(){
const {newNotifications} = this.props.notifications;
return(
<div className="TopNavbar">
<div className="NavbarLastSection">
<span className="TopNavbarNotification" onClick={this.toggleNotificationMenu}>
{newNotifications.length === 0 ? <i className="TopNavbarNotificationIcon"><a><FontAwesomeIcon icon="bell"/></a></i>
: <i className="TopNavbarNotificationIcon" style={style}><a><FontAwesomeIcon icon="bell"/></a></i>}
{newNotifications.length === 0 ? null : <span className="NotificationBox">{newNotifications.length}</span>}
</span>
</div>
</div>
)
}
};
const mapStateToProps = state => ({
notifications: state.notifications,
error: state.error
});
const mapActionsToProps = {
viewNotifications
};
export default connect(mapStateToProps, mapActionsToProps)(TopNavbar);
Seems your problem is the notifications prop is set to undefined when mounted.似乎您的问题是通知道具在安装时设置为未定义。 As your linking your state.notifications i would suggest to ensure that value is always an object with newNotifications in it
当您链接您的 state.notifications 时,我建议确保该值始终是 object,其中包含 newNotifications
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.