Как добавить объект в массив amp-state в AMP-HTML? - PullRequest
1 голос
/ 20 октября 2019

У меня есть состояние под названием currentItem с url, title, description ... Когда я нажимаю кнопку, currentItem должен быть сохранен в другом состоянии, называемом myItems. Он будет содержать список объектов предметов.

Проблема сейчас заключается в том, что всегда показывает последний элемент , поэтому он перезаписывает весь список для каждой отправки currentItem.

Мои состояния:

    <amp-state id="currentItem">
        <script type="application/json">
            {
                "url": "",
                "imageUrl": "",
                "title": "",
                "description": ""
            }
        </script>
    </amp-state>
    <amp-state id="myItems">
        <script type="application/json">
            []
        </script>
    </amp-state>

Определение списка:

<amp-list class="mt3"
          layout="fixed-height"
          height="0"
          [src]="myItems"
          [height]="myItems.length * 200"
          items="."
          binding="no">
<template type="amp-mustache">
...
</template>

Действие по добавлению currentItem в список:

<button type="button"
        on="tap:AMP.setState({ myItems: [currentItem]})">
Add
</button>

Я пытался использовать AMP. setState ({myItems: myItems.concat (currentItem)}), но происходит сбой, также с +. Как я могу это сделать?

1 Ответ

3 голосов
/ 20 октября 2019

concat ожидает массив. Вот рабочая версия:

 <amp-state id="currentItem">
    <script type="application/json">
      {
        "url": "url",
        "imageUrl": "imageUrl",
        "title": "title",
        "description": "desc"
      }
    </script>
  </amp-state>
  <amp-state id="myItems">
    <script type="application/json">
      []
    </script>
  </amp-state>
  <h1>Hello AMPHTML World!</h1>
  <amp-list class="mt3" layout="fixed-height" height="0" [src]="myItems" [height]="myItems.length * 200" items="." binding="no">
    <template type="amp-mustache">
      Item: {{title}}
    </template>
  </amp-list>
  <button type="button" on="tap:AMP.setState({ 
                                myItems: myItems.concat([currentItem])
                            })">
    Add
  </button>
...