You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Polymer中点击按钮导航数组元素:是否需Redux?可直接实现吗?

回答你的问题

首先明确说:完全不需要使用Redux这类工具,这个场景属于组件内部的局部状态管理,Polymer本身就可以完美实现,而且代码非常简洁。

下面是修改后的完整组件代码,我会一步步解释改动点:

<dom-module id="my-quiz">
  <template>
    <div>Employee List</div>
    <!-- 显示当前员工的信息 -->
    <div class="current-employee">
      <p>Name: [[currentEmployee.name]]</p>
      <p>ID: [[currentEmployee.id]]</p>
    </div>
    <button on-click="prev" disabled="[[isFirst]]">Previous</button>
    <button on-click="next" disabled="[[isLast]]">Next</button>
  </template>
  <script>
    class Quiz extends Polymer.Element {
      static get is() { return 'my-quiz'; }

      // 定义响应式属性,这样属性变化时UI会自动更新
      static get properties() {
        return {
          employees: {
            type: Array,
            value: () => [
              { name: 'Bob', id: 'b1' },
              { name: 'Ayesha', id: 'b2' },
              { name: 'Fatma', id: 'b3' },
              { name: 'Tony', id: 'b5' }
            ]
          },
          currentIndex: {
            type: Number,
            value: 0
          },
          currentEmployee: {
            type: Object,
            computed: '_computeCurrentEmployee(currentIndex, employees)'
          },
          isFirst: {
            type: Boolean,
            computed: '_computeIsFirst(currentIndex)'
          },
          isLast: {
            type: Boolean,
            computed: '_computeIsLast(currentIndex, employees.length)'
          }
        };
      }

      // 计算当前显示的员工对象
      _computeCurrentEmployee(index, employees) {
        return employees[index] || {};
      }

      // 判断是否是第一个员工,控制上一个按钮禁用状态
      _computeIsFirst(index) {
        return index === 0;
      }

      // 判断是否是最后一个员工,控制下一个按钮禁用状态
      _computeIsLast(index, total) {
        return index === total - 1;
      }

      prev() {
        if (this.currentIndex > 0) {
          this.currentIndex--;
        }
      }

      next() {
        if (this.currentIndex < this.employees.length - 1) {
          this.currentIndex++;
        }
      }
    }

    window.customElements.define(Quiz.is, Quiz);
  </script>
</dom-module>

关键改动说明:

  • 新增了currentIndex属性来跟踪当前显示的员工位置,初始值为0(第一个员工)。
  • 使用Polymer的计算属性(currentEmployee、isFirst、isLast)来自动推导UI需要的状态,比如当前员工信息、按钮是否该禁用。
  • 给prev和next方法添加了边界检查,避免索引越界,同时通过修改currentIndex来切换员工——因为currentIndex是响应式属性,它的变化会自动触发计算属性更新,进而更新UI。
  • 给按钮添加了disabled属性,当处于第一个/最后一个员工时,对应的按钮会灰掉,提升用户体验。

关于Redux的使用场景:

Redux这类工具适合全局状态管理或者跨多个组件共享状态的场景(比如用户登录状态、购物车数据等)。而你的需求只是单个组件内部的状态切换,完全不需要引入额外的状态管理库,Polymer自身的响应式属性和计算属性就足够解决问题了。

内容的提问来源于stack exchange,提问作者user3310115

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:35:10