使用react-notification-system
,每次尝试从后端返回JSON数组时,我都试图创建一个弹出通知。为了显示问题,我手动添加了数组并在下面的代码中对其进行了解析。
看来,如果alerts
数组的“类型”为“警告”或“错误”,我希望触发该事件,并在“消息”部分中打印附带的消息。
我很确定我遇到的问题是状态和道具。现在,运行此代码,我得到Uncaught TypeError: Cannot read property 'type' of undefined
-这引出了一个问题,如何正确访问React中数组中的信息,并在条件下在return函数中触发它?
样例代码:
var NotificationSystem = React.createClass({
_notificationSystem: null,
_addNotification: function(event) {
event.preventDefault();
this._notificationSystem.addNotification({
message: 'Danger!',
level: 'error',
position: 'tc'
});
},
componentDidMount: function() {
this._notificationSystem = this.refs.notificationSystem;
},
render: function() {
var mdata = {"alerts":[
{
"dateTime": 111111111,
"message": "This is a super serious warning",
"type": "WARNING"
}
]};
var mdataArr = Object.values(mdata);
console.log(JSON.stringify(mdataArr)); // It prints the JSON in console
if (this.props.mdataArr.type == "WARNING")
this._notificationSystem.addNotification({
message: this.props.mdataArr.message,
level: 'warning',
position: 'tc'
});
else if (this.props.mdataArr.type == "ERROR")
this._notificationSystem.addNotification({
message: this.props.mdataArr.message,
level: 'error',
position: 'tc'
});
return (
<div>
<NotificationSystem ref="notificationSystem" />
</div>
);
}
});
最佳答案
实际上,您在mdataArr
方法本身中定义了render()
,但是您正在this.props
中寻找相同的内容
在渲染方法中尝试一下
if (mdataArr[0].type == "WARNING")
this._notificationSystem.addNotification({
message: mdataArr[0].message,
level: 'warning',
position: 'tc'
});
else if (mdataArr[0].type == "ERROR")
this._notificationSystem.addNotification({
message: mdataArr[0].message,
level: 'error',
position: 'tc'
});