【问题标题】:How to calculate array while rendering [Vue.js] - Infinite loop error如何在渲染时计算数组 [Vue.js] - 无限循环错误
【发布时间】:2022-01-06 16:55:09
【问题描述】:

这是我在父组件中的代码:

                   <div
                            v-for="measurement
                             in measurements"
                            :key="measurement.id"
                   >
                            <graph-component
                                :value="valueOfMeasurement(measurement)"
                            ></graph-component>
                  </div>

我将 props value 发送给子组件 graph-component:value 应该将数组发送到 graph-component 但我收到错误 You may have an infinite update loop in a component render function.

方法valueOfMeasurement(measurement)是:

methods:{

     valueOfMeasurement(measurement) {
                this.arrayOfValues.length=0;
                this.counter=0;
    
                for( this.counter;this.counter<this.message.feeds.length;this.counter++)
                {
                     this.arrayOfValues.push(this.message.feeds[this.counter]["field" + measurement.fieldId]);
                }
                return this.arrayOfValues;
                
            }
}

我是 Vue.js 的初学者,我假设我收到此错误是因为我将新元素推送到数组,但我找不到其他方法来做到这一点。

【问题讨论】:

    标签: javascript vue.js vue-props


    【解决方案1】:

    您可能会出现无限循环,因为您在渲染期间正在改变状态。具体来说,您在渲染期间(即在模板中)调用valueOfMeasurement 方法,该方法正在修改组件状态(this.arrayOfValuesthis.counter)。这将触发 Vue 再次重新渲染,然后再次改变状态,以此类推。

    为什么arrayOfValuescounter 是本地状态?无论如何,您只是在每次调用该方法时都清除它们,因此它们似乎应该只是该方法中的局部变量。 但是...这取决于&lt;graph-component&gt; 是否会改变这些数组;如果是这样,您应该提前在模板之外预先计算所有这些数据,也许是在首次设置 measurements 或在 created 挂钩等时。

    【讨论】:

    • 就是这样。我有一个错误的想法,我需要在数据中声明它,这样它就不会给我无限循环。
    猜你喜欢
    • 2021-06-28
    • 2021-01-12
    • 2010-12-24
    • 2019-01-07
    • 2018-11-29
    • 2021-09-05
    • 2020-09-17
    • 2021-05-17
    • 2021-02-04
    相关资源
    最近更新 更多