【问题标题】:React-notification-system - trigger notification on JSON inputReact-notification-system - 在 JSON 输入上触发通知
【发布时间】:2026-01-30 08:30:01
【问题描述】:

使用react-notification-system,我试图在每次从后端返回 JSON 数组时创建一个弹出通知。为了显示问题,我手动添加了数组并在下面的代码中对其进行了解析。

如果alerts 数组的“类型”是“警告”或“错误”,我希望触发该事件,并在“消息”部分打印随之而来的消息。

我很确定我遇到的问题与状态和道具有关。现在,运行这段代码,我得到了Uncaught TypeError: Cannot read property 'type' of undefined - 这让我想到了一个问题,我如何在 React 中正确访问数组内的信息,并在条件的返回函数中触发它?

示例代码:

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

【问题讨论】:

    标签: javascript arrays json reactjs


    【解决方案1】:

    实际上您在render() 方法本身中定义了mdataArr,但您在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'
            });
    

    【讨论】:

    • 用你的方法,console.log(mdataArr[0].type]不打印任何信息?