Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

javascript - "You may have an infinite update loop in a component render function" warning in Vue component

I'm creating a basic table with a sorting feature:

<template>
  <!-- more code -->
  <tr v-for="item in sortBy(data.body, { name: 'name', order: 1 })">
    <td v-for="field in item">{{ field }}</td>
  </tr>
  <!-- data.body => [{ name: Group 1 }, { name: Group2 }, // etc.] -->
</template>

props: {
  data: {
    type: Object,
    default () {
      return {}
    }
  }
},

methods: {
  sortBy (data, params) { 
    // the warning disappears if I only leave "return data"
    data.sort((a, b) => {
      return a[params.name] - b[params.name] * params.order
    })
    return data
  }
}

For some reason, I'm getting this warning:

[Vue warn]: You may have an infinite update loop in a component render function.

Why is this is and how to fix it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're getting the warning because you're changing the value of data.body within sortBy. This data change will cause the render function to run again. The reason you're not getting an infinite loop is that on the second call to sortBy the data is already sorted which results in no data change to data.body.

The solution is what Jaromanda X mentioned. Using slice will make a copy of the array which means data.body will not change in value, and therefore no re-render will be called.

return data.slice().sort(....

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...