繁体   English   中英

反应:OnClick 无法设置未定义错误反应的属性“长度”

[英]React: OnClick Cannot Set Property 'length' Of Undefined Error React

在以下代码中,我单击通知图标并调用 toggleNotificationMenu function 以便 viewNotifications 操作可以触发。 但是,当我这样做时,我收到以下错误:“无法读取未定义的属性'长度'”,这与 newNotifications 有关。 但是,当我 console.log newNotifications 我可以看到它成功显示了一个包含对象的数组。 viewNotifications 操作确实成功触发,因为我可以看到在我的数据库中所做的更改。 我只是无法弄清楚为什么我会收到错误消息。

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

似乎您的问题是通知道具在安装时设置为未定义。 当您链接您的 state.notifications 时,我建议确保该值始终是 object,其中包含 newNotifications

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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