【问题标题】:Avoiding Content re-fetching when State has already populated当状态已经填充时避免重新获取内容
【发布时间】:2017-10-14 06:28:50
【问题描述】:

我有以下 Vue 组件结构:

Wrapper
-- QuestionsList
---- Question
-- QuestionDetail

还有以下路线:

/ (goes to Questionslist)
/:id (goes to QuestionDetail)

当用户访问/ 时,会完成一个 HTTP GET 请求(通过 Vuex),并且内容会填充到对象数组中。然后,如果他点击“显示更多”链接,他会看到 QuestionDetail 页面(但无需重新获取内容 - 它直接取自 State

我的问题是,每次我们在页面中“路由”时,我们都不知道 Store 的状态。

例如,当用户导航(深度链接)到 /:id 时,我们需要查看 State 是否已填充,因此避免创建新的 HTTP GET:

created() {
  if (!this.$store.state.questions.length) {
    this.$store.dispatch('requestItems');
  }
},
computed: {
  question() {
    return this.$store.state.questions[this.$route.params.id] || {};
  },
},

在不同的场景中,由于我总是将获取的新项目与当前状态相连接,因此我经常看到数据重复:

  [types.FETCHED_ADS_SUCCESS](state, payload) {
    state.items = [...state.items, ...payload]; // when I go back in history, a new action is initiated and concats a copy of the same data
  },

【问题讨论】:

    标签: javascript vue.js redux vuex


    【解决方案1】:

    您的商店结构是什么?我发现在商店中保留一个布尔指示器来指示内容是否已加载很有用。

    const store = new Vuex.store({
      state: {
        questions: {
          isLoaded: false,
          items: []
        }
      }
    })
    

    然后在您获取问题的组件中检查此内容并在加载后更新。

    【讨论】:

    • 有趣。我认为这是一个可行的快速解决方案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-28
    • 2013-03-13
    • 1970-01-01
    • 2017-12-03
    • 2021-07-16
    • 2021-12-12
    • 2017-04-18
    相关资源
    最近更新 更多