当我尝试将数据放入这些对象时,使用 Vuex 操作获取数据对象并获得“未捕获承诺TypeError”

问题描述

我正在学习 Vuex,以及最近我用来获取数据的操作。

似乎一切正常,我可以访问我的电影对象,我可以选择该对象中的任何电影......但是一旦我想访问其中一部电影中包含的数据,错误消息就会唤醒我的控制台。

Vuex:

export default createStore({
  state: {
    films: []
  },mutations: {
    SET_FILMS(state,films) {
      state.films = films
    }
  },actions: {
    fetchFilms({ state,commit }){
        services_movieDB.getFilms('')
        .then(response => {
          commit('SET_FILMS',response.data.results)
        })
        .catch(error => console.log("error with api call getFilms() in CardFilms",error))
      }

    }
});

*services_movieDB 是一个使用 Axios 获取数据的服务。为了让这个问题更清楚,我会省去这部分:它有效。

组件:

<template>
  <section>
    {{ films[currentIndex] }} //it works: no error message
    {{ films[currentIndex] }} //it works: but 2 warnings and 1 error message in the console
    {{ currentFilm }} //isn't work
  </section>
</template>

<script>
import { mapState } from "vuex";

export default {
  name: "CardFilms",data() {
    return {
      currentIndex: 0,currentFilm: null
    };
  },computed: {
    ...mapState(["films"]),},beforeCreate(){
    this.$store.dispatch("fetchFilms")
    this.currentFilm = this.$store.state.films[this.currentIndex]
  },};
</script>

警告:

[Vue warn]: Unhandled error during execution of render function 
  at <CardFilms> 
  at <Acceuil onVnodeUnmounted=fn<onVnodeUnmounted> ref=Ref< undefined > > 
  at <RouterView> 
  at <App> 
[Vue warn]: Unhandled error during execution of scheduler flush. This is likely a Vue internals bug. Please open an issue at https://new-issue.vuejs.org/?repo=vuejs/vue-next 
  at <CardFilms> 
  at <Acceuil onVnodeUnmounted=fn<onVnodeUnmounted> ref=Ref< undefined > > 
  at <RouterView> 
  at <App>

错误

Uncaught (in promise) TypeError: can't access property "title",_ctx.films[$data.currentIndex] is undefined

这真的是 Vue 内部错误吗?有人身体有办法吗? VueJS 3 | Vuex 4

解决方法

添加条件渲染 (v-if),这样您就不会在没有数据的情况下进行渲染。

 <section v-if="currentFilm && films">

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...