0

初めてテンプレート リテラルを使用しようとしていますが、他のリソースをいくつか読んだ後にデバッグできないエラーが発生しています。

$.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>
    `;
}

コンソールのエラー メッセージは次のとおりです。

Uncaught TypeError: not read property created_at of undefined を note.created_at と比較しようとすると、未定義のプロパティを読み取ることができませんnull

プロパティにアクセスするためにドット表記を使用するのが好きではないようで、現時点ではデバッグするにはあまりにも無知であるという根本的に間違ったことをしたと思います。

基本的には、json オブジェクトをテンプレート リテラルに渡し、そのプロパティを使用してコンポーネントを構築し、条件なども使用できるようにしたいだけです。

4

1 に答える 1

2

あなたの問題は、関数を次のように宣言していることです。

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

于 2016-12-21T11:03:10.233 に答える