问题

如何将参数传递给 getter 内的 mapGetters ?这是同时对 widgetFetched.postsposts 的状态变化使用react的正确方法吗?换句话说,我的 getter 可以对这些变化使用react吗?

解释

我试图通过 State 使我的组件对 Vuex Storegetter 的变化使用react。为了实现这一点,我在我的组件中使用了 mapGetters。但是这个 getter 接收一个参数,一个 id 来过滤我的状态(即扁平化)。

我有两个状态(即字典): widgetsFetchedposts 。一个 widgetFetched 有一个名为 posts 的属性,它是一个 Post.Id 数组。状态 posts 是一个字典,其键是 Post.Id

所以,我有一个名为 gettergetPostsByWidgetId ,它接受一个参数 widgetId 。然后,我的 getter 返回一个包含由 widgetFetched.posts 的 id 过滤的帖子的数组。

店铺

const store = new Vuex.Store({
  state: {
    widgetsFetched: {
        1: { id: 1, done: true, posts: [1, 2, 3, 4] },
        2: { id: 2, done: false, posts: [5, 6] }
    },
    posts: {
        1: { name: '...', id: 1, content: '...' },
        2: { name: '...', id: 2, content: '...' },
        3: { name: '...', id: 3, content: '...' },
        4: { name: '...', id: 4, content: '...' },
        5: { name: '...', id: 5, content: '...' },
        6: { name: '...', id: 6, content: '...' }
    }
  },
  getters: {
    getPostsByWidgetId: (state, getters) => (widgetId) => {
      if (widgetId && state.widgetsFetched[widgetId] && state.widgetsFetched[widgetId].posts) {
        return state.widgetsFetched[widgetId].posts.map((postId) => {
          return state.posts[postId]
        })
      }
    }
  }
})

成分

我的组件看起来像:
<template>
  <div>
    <p v-for="post in posts(this.widget._id)" >{{ post.id }} - {{ post.score }}</p>
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'

  export default {
    name: 'reddit',
    props: ['widget'],
    computed: {
      ...mapGetters({
        posts: 'getPostsByWidgetId'
      })
    }
  }
</script>

<style scoped>
</style>

例子

javascript - VueJS : React to State change through mapGetters receiving arguments-LMLPHP

javascript - VueJS : React to State change through mapGetters receiving arguments-LMLPHP

最佳答案

目前,mapGetters 不支持传递参数。但是您可以使用以下代码实现类似的效果:

computed: {
  posts() {
    return this.$store.getter.getPostsByWidgetId(this.widget._id)
  }
}

关于javascript - VueJS : React to State change through mapGetters receiving arguments,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46484382/

10-11 12:50
查看更多