javascript [Vue 警告]:渲染函数中的错误:“TypeError:无法读取 null 的属性‘first_name’”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46897776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 07:01:25  来源:igfitidea点击:

[Vue warn]: Error in render function: "TypeError: Cannot read property 'first_name' of null"

javascriptvue.jsvuex

提问by Mateusz Urbański

I have the following Navigation.vuecomponent:

我有以下Navigation.vue组件:

<template>
  <div>
    {{user.first_name}}
  </div>
</template>

<script>
  import { mapActions, mapGetters } from 'vuex'

  export default {
    name: 'hello',
    methods: {
      ...mapActions(['myAccount'])
    },

    mounted: function () {
      if (localStorage.getItem('access_token')) {
        this.myAccount()
      }
    },

    computed: {
      ...mapGetters(['user'])
    }
  }
</script>

This code returns:

此代码返回:

[Vue warn]: Error in render function: "TypeError: Cannot read property 'first_name' of null"

but the strange thing is that user first name is showing correctly. What am I doing wrong?

但奇怪的是用户名显示正确。我究竟做错了什么?

回答by thanksd

You are most likely getting that error because userin your Vuex store is initially set to null. The usergetter mapped to your Vue component is returning that nullvalue before some initialization to the Vuex store properly sets the user.

您很可能会收到该错误,因为user在您的 Vuex 商店中最初设置为null. user映射到 Vue 组件的getternull在对 Vuex 存储进行一些初始化正确设置user.

You could initially set the userto an empty object {}. This way, user.first_namein your Vue component's template will be undefinedand nothing will be rendered in the template.

您可以最初将 设置user为空对象{}。这样,user.first_name在您的 Vue 组件的模板中undefined,将不会在模板中呈现任何内容。



Alternatively, you could add a v-if="user"attribute to the containing divelement:

或者,您可以v-if="user"向包含div元素添加一个属性:

<div v-if="user">
  {{ user.first_name }}
</div>

This way, the divand its contents will not be rendered until the value of the mapped userproperty is truthy. This will prevent Vue from trying to access user.first_nameuntil the useris properly set.

这样,在div映射user属性的值为真值之前,将不会呈现 和它的内容。这将阻止 Vueuser.first_nameuser正确设置之前尝试访问。

回答by user1925711

A solution that worked for me was to set the user to an empty string ' 'instead of null.

对我有用的解决方案是将用户设置为空字符串' '而不是 null。

const state = {
    user: ''
}