如何将对象添加到 AMP-HTML 中的 amp-state 数组?

Noi*_*oiK 2 amp-html amp-bind amp-list

我有一个名为 currentItem 的状态,其中包含 url、标题、描述...当我按下按钮时,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>
Run Code Online (Sandbox Code Playgroud)

列表定义:

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

将 currentItem 添加到列表的操作:

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

我尝试使用 AMP.setState({ myItems: myItems.concat(currentItem)}) 但它崩溃了,也与 + 一起崩溃。我怎样才能做到这一点?

Seb*_*enz 5

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>
Run Code Online (Sandbox Code Playgroud)