【问题标题】:TypeError: Cannot set property 'words' of undefinedTypeError:无法设置未定义的属性“单词”
【发布时间】:2018-07-23 13:21:47
【问题描述】:

我的 vuex 商店中有这个动作:

loadExercises ({commit}) {
  commit('setLoading', true)
  const db = firebase.firestore()
  db.collection('exercises').get()
    .then(querySnapshot => {
      const exercises = []
      querySnapshot.forEach((doc) => {
        exercises.push({
          title: doc.data().title,
          language: doc.data().language,
          translated: doc.data().translated,
          lastOpen: doc.data().lastOpen,
          dueDate: doc.data().dueDate,
          uid: doc.data().uid,
          userId: doc.data().userId,
          words: [{ word: '', uid: '', translation: '' }]
        })
        db.collection('exercises').doc(doc.data().uid).collection('words').get()
          .then(words => {
            const wordsArray = []
            words.forEach(word => {
              wordsArray.push(word.data())
            })
            let exercise = this.getters.loadedExercise(doc.data().uid)
            exercise.words = wordsArray
          })
          .catch(error => {
            commit('setLoading', false)
            console.log(error)
          })
      })
      commit('setLoading', false)
      commit('setLoadedExercises', exercises)
    })
    .catch(error => {
      commit('setLoading', false)
      console.log(error)
    })
}

它应该从 firebase cloudstore 数据库中获取练习。它适用于某些路线,但不是全部。

当使用这两个 getter 时,它可以工作:

loadedExercises (state) {
  return state.loadedExercises
},
loadedExercise (state) {
  return (exerciseId) => {
    return state.loadedExercises.find(exercise => {
      return exercise.uid === exerciseId
    })
  }
}

但是当我使用这些吸气剂时:

upcomingExercises (state, getters) {
  return getters.loadedExercises.filter(exercise => {
    return exercise.dueDate > 0
  })
},
latestExercises (state, getters) {
  return getters.loadedExercises.splice(0, 5)
},

它不起作用我只是得到“TypeError:无法设置未定义的属性'words'”。我做错了什么?

【问题讨论】:

  • 我建议你去console 看看words 的属性是否存在。对我来说,这似乎不是 vuex 的问题,而是因为数据/对象(具有属性words)不存在。

标签: firebase vue.js google-cloud-firestore vuex


【解决方案1】:

在我看来,您没有将值返回给函数。

尝试替换

db.collection('exercises').get()

return db.collection('exercises').get()

db.collection('exercises').doc(doc.data().uid).collection('words').get()

return db.collection('exercises').doc(doc.data().uid).collection('words').get()

【讨论】:

  • 有点效果,我在前 5 次练习中遇到了同样的错误,然后它就可以正常工作了。我应该如何解决这个问题?
  • 我会采纳 @kevguy 的建议,在代码的每一步添加一个 console.log,看看哪里出了问题
猜你喜欢
  • 2015-09-09
  • 2021-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-20
  • 2022-08-16
相关资源
最近更新 更多