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

Polymer 2中使用Axios获取数据后无法修改数组问题

修复Polymer 2无限滚动数据更新问题

核心问题分析

  1. this指向错误:直接将scrollDetection绑定到window.scroll事件时,方法内的this指向window而非组件实例,导致无法访问组件的users属性和Polymer的响应式方法。
  2. 请求参数错误:滚动触发的请求中results参数为空,无法获取有效用户数据。
  3. 无加载状态控制:滚动到底部时可能多次触发请求,造成重复加载。
  4. 数组更新方式错误:this.users.push = response.data.results是语法错误,且直接使用原生push不会触发Polymer的视图更新,必须使用Polymer提供的this.push()方法。

修复后的完整代码

<link rel="import" href="../../bower_components/polymer/polymer-element.html">
<link rel="import" href="../../bower_components/polymer/lib/elements/dom-repeat.html">

<dom-module id="infinitescroll-component">
  <template>
    <style>
      :host {
        display: block;
        margin: 15px;
      }
    </style>

    <template is="dom-repeat" items="[[users]]" as="user">
      <p>[[user.name.first]]</p>
      <p>[[user.name.last]]</p>
      <hr>
    </template>
  </template>

  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

  <script>
    class InfiniteScroll extends Polymer.Element {
      static get is() {
        return 'infinitescroll-component';
      }
      static get properties() {
        return {
          users: {
            type: Array,
            value: function () {
              return [];
            }
          },
          isLoading: {
            type: Boolean,
            value: false
          }
        }
      }

      connectedCallback() {
        super.connectedCallback();
        this.getInitialUsers();
      }

      getInitialUsers() {
        axios.get(`https://randomuser.me/api/?results=20`).then((response) => {
          this.users = response.data.results;
        });
      }

      ready() {
        super.ready();
        // 使用箭头函数绑定this指向组件实例
        window.addEventListener('scroll', () => this.scrollDetection());
      }

      scrollDetection() {
        if (this.isLoading) return;

        let bottomOfWindow = document.documentElement.scrollTop + window.innerHeight === document.documentElement.offsetHeight;
        if (bottomOfWindow) {
          this.isLoading = true;
          // 修正请求参数,获取1条数据
          axios.get(`https://randomuser.me/api/?results=1`).then(response => {
            // 使用Polymer的push方法触发响应式更新
            this.push('users', ...response.data.results);
            this.isLoading = false;
          }).catch(() => {
            this.isLoading = false;
          });
        }
      }
    }

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

关键修复点说明

  • 绑定正确的this:在ready方法中用箭头函数() => this.scrollDetection()绑定事件,确保scrollDetection内的this指向组件实例。
  • 修正请求参数:将请求URL改为https://randomuser.me/api/?results=1,明确获取1条用户数据。
  • 添加加载状态:新增isLoading属性,在请求发起时设为true,请求完成后设为false,避免重复触发请求。
  • 正确更新数组:使用Polymer提供的this.push('users', ...response.data.results)方法,展开获取到的结果数组并添加到users中,触发视图自动更新。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 08:35:25