最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin4浏览0评论

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?

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?

Share Improve this question edited Nov 20, 2017 at 3:05 alex asked Nov 20, 2017 at 3:00 alexalex 7,60115 gold badges53 silver badges79 bronze badges 1
  • 6 well, it's a warning not an error :p try return data.slice().sort(...... – Jaromanda X Commented Nov 20, 2017 at 3:04
Add a comment  | 

1 Answer 1

Reset to default 21

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(....

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论