【问题标题】:Error Trying to use JSON Objects with JavaScript ES6 Template Literals尝试将 JSON 对象与 JavaScript ES6 模板文字一起使用时出错
【发布时间】:2016-12-21 19:31:28
【问题描述】:

我第一次尝试使用模板文字,但在阅读了一些其他资源后遇到了无法调试的错误。

$.ajax({
    // usual things
    success: function(data) {
        // add a manual note before looping through the ones returned via ajax
        var nowNote = { status: `now`, text: `Now`, created_at: null };
        var notes = data.notes;

        var timeline =  `

            ${noteTemplate({ nowNote })}

        `;
        // take out ${timelineTemplate({ notes })} for now
    }
});

var timelineTemplate = ({ notes }) => {
    return `
        ${notes.map(note => noteTemplate({
            note
        })).join('')}
    `;
}

var noteTemplate = ({ note }) => {
    return `

       ${note.created_at == null ?
           ''
       : `<strong>${moment(note.created_at).format('DD/MM/YYYY HH:mm')}</strong>`}

       <span>${note.text.replace(/(?:\r\n|\r|\n)/g, '<br>')}</span>
    `;
}

控制台上的错误信息是:

未捕获的类型错误:尝试将 note.created_at 与 null 进行比较时,无法读取未定义的属性 created_at。

它似乎不喜欢使用点符号来访问属性,这让我觉得我做了一些根本错误的事情,我现在太无知了,无法调试。

基本上我只想将一个 json 对象传递给模板文字,并使用它的属性从它构建一个组件,同时还能够使用条件等。

【问题讨论】:

    标签: javascript ecmascript-6 template-literals


    【解决方案1】:

    您的问题是您将函数声明为:

    var noteTemplate = ({ note }) => {
        return `
    
           ${note.created_at == null ?
               ''
           : `<strong>${moment(note.created_at).format('DD/MM/YYYY HH:mm')}</strong>`}
    
           <span>${note.text.replace(/(?:\r\n|\r|\n)/g, '<br>')}</span>
        `;
    }
    

    所以它正在检测一个具有名为note 的属性的对象。

    您可以删除声明中的大括号或作为参数传递 {note: nowNote} 而不仅仅是 note

    【讨论】:

    • 啊,好的。非常感谢@Pablo。
    猜你喜欢
    • 1970-01-01
    • 2017-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-12
    • 2020-03-15
    相关资源
    最近更新 更多