javascript - React-notification-system - 在 JSON 输入上触发通知

标签 javascript arrays json reactjs

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

看起来,如果alerts数组的“类型”是“警告”或“错误”,我希望触发该事件,并进一步在“消息”部分。

我很确定我遇到的问题与状态和 Prop 有关。现在,运行这段代码,我得到了 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>
        );
    }
});

最佳答案

实际上,您在 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'
        });

关于javascript - React-notification-system - 在 JSON 输入上触发通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41680655/

相关文章:

javascript - 将月数添加到文本字段中的日期

javascript - 来自 cookie 和勾选框的字符串的 JSON 解析不会勾选框

javascript - 如何将 MSAL(用于 js 的 Microsoft 身份验证库)正确导入并使用到 javascript(非 typescript ) react 单页应用程序中?

javascript - 应用程序启动时未调用 Phonegap handleOpenURL (iOS)

android - 通过 Intent 传递 Number[] 数组

python - 如何将类似字典的字符串转换为字典?

javascript - JS 查找丢失的字母(字母表 - 数组)

java - 如何按照我添加的顺序获取 JInternalFrame

javascript - 获取 JSON 字符串时出现问题

python - 给定一个字符串,如何返回 json 路径?