通过 nuxt.js 正确使用 mapActions

Using mapActions correctly with nuxt.js

我需要在 nuxt.js 商店中使用 mapActions。

如果我调用“dispatch”方法一切正常,但是当我使用 mapActions 时我得到 'Maximum call stack size exceeded' 错误。

// storequiz.js

export const state = () => ({
  quizVersion: null,
  stage: null,
  title: null,
  img: null,
  questions: [],
  currentQuestion: null,
  answers: [],
})

export const mutations = {
  setQuizVersion(state, version) {
    state.quizVersion = version
  },
  setQuestions(state, questions) {
    state.questions = questions
  },
  
}

export const actions = {
  async fetchData({ commit }, payload) {
    const res = await this.$axios.get(payload)
    commit('setQuizVersion', res.data.version)
    commit('setQuestions', res.data.questions)
  },
}

// 我的方法:

methods: {
    ...mapActions({
      fetchData: 'storequiz/fetchData',
     }),
    async fetchData() {
      // await this.$store.dispatch('storequiz/fetchData', this.url)
      await this.fetchData(this.url)
    },
....

我收到错误:

error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE
client.js?06a0:103 RangeError: Maximum call stack size exceeded
    at new Context (runtime.js?96cf:449)
    at Object.wrap (runtime.js?96cf:41)
    at _callee2 (Quiz.vue?b7d7:182)
    at eval (asyncToGenerator.js?1da1:22)
    at new Promise (<anonymous>)
    at eval (asyncToGenerator.js?1da1:21)
    at VueComponent.fetchData (Quiz.vue?b7d7:182)
    at _callee2$ (Quiz.vue?b7d7:182)
    at tryCatch (runtime.js?96cf:63)
    at Generator.invoke [as _invoke] (runtime.js?96cf:293)    

如果我使用:await this.$store.dispatch('storequiz/fetchData', this.url) 而不是 await this.fetchData(this.url),一切正常。

我在这里错过了什么?

映射的fetchData被后续的同名方法隐藏。您应该将其中之一重命名为唯一的方法名称(如果它们都需要)。

此外,组件方法 fetchData 无条件地调用自身,因此存在导致 Maximum call stack size exceeded 的无限循环。添加条件以跳出循环(如果甚至需要此调用)。