可以在构造函数中获取值,但是在render函数中输出TypeError: Cannot read property 'xxx' of undefined

Posted

技术标签:

【中文标题】可以在构造函数中获取值,但是在render函数中输出TypeError: Cannot read property \'xxx\' of undefined【英文标题】:The value can be obtained in the constructor function, but TypeError: Cannot read property'xxx' of undefined is output in the render function可以在构造函数中获取值,但是在render函数中输出TypeError: Cannot read property 'xxx' of undefined 【发布时间】:2021-02-20 09:37:36 【问题描述】:

下面代码的console.log (data ["users"] ["userId"] ["points"])getData ()中,输出20。

但是在render () <Text> JSON.stringify (this.state.users.userId.points) </ Text> 当你运行时

TypeError: 无法读取未定义的属性“点” 输出错误。

我如何JSON.stringify (this.state.users.userId.points) Text> 可以输出为20吗?

import React from 'react';
import  Text, View, Button, StyleSheet, TouchableHighlight, FlatList from 'react-native';
import  FloatingAction  from "react-native-floating-action";
import Icon from 'react-native-vector-icons/FontAwesome5';
import * as firebase from 'firebase';
import 'firebase/firestore';
import env from '../../env.json';

interface Props 
  navigation: any;
  route:any;
  authorId:string;
  postId:string;
  userId:string;
  win:string;
  wni:string;
  ideas:any;
  

  interface State 
    actions:
      text:string,
      icon:JSX.Element,
      name:string,
      position:number
    [],
    data:any,
    points:number
    users:any
  

  const firebaseConfig = 
    apiKey: env.apiKey,
    authDomain: env.authDomain,
    databaseURL: env.databaseURL,
    projectId: env.projectId,
    storageBucket: env.storageBucket,
    messagingSenderId: env.messagingSenderId,
    appId: env.appId,
    measurementId: env.measurementId
  ;

  if (firebase.apps.length === 0) 
    firebase.initializeApp(firebaseConfig);
  

  const db = firebase.firestore();

  export class Rank extends React.Component<Props,State> 
      constructor(props)
          super(props)
          this.state = 

            actions:[
              
                text: "Write down features",
                icon: <Icon name="list" size=20/>,
                name: "feature",
                position: 2
              ,
              
                text: "Post your idea",
                icon: <Icon name="lightbulb" size=20/>,
                name: "idea",
                position: 1

              
            ],
            data:,
            points:0,
            users:
          

          this.getData()
      

      async getData()
        let firestoreData = await db.collection("posts").doc(this.props.route.params.postId).get()
        let data = firestoreData.data()

        this.setState(
          data:data,
          users:data["users"]

        )

        console.log(data["users"]["userId"]["points"])
      

      render()
        return (
            <View
            style=styles.backgroundImage
            >
        <Text>JSON.stringify(this.state.users.userId.points)</Text>
            </View>
        )
      
  

  const styles = StyleSheet.create(
    backgroundImage: 
        ...StyleSheet.absoluteFillObject,
      ,
  )

【问题讨论】:

【参考方案1】:

根据您的错误 this.state.users.userId 未定义,因此当您尝试获取未定义点时代码失败。尝试一个一个地解构对象并逐步查看会发生什么,我认为您在第一次渲染中遇到此错误,其中状态中没有任何内容,因此它会因此错误而失败。试试下面的代码,看看会发生什么。

render()
    const  userId  = this.state.users;
    return (
        <View
        style=styles.backgroundImage>
        <Text>userId ? JSON.stringify(userId.points): "Loading data.."</Text>
        </View>
    )

【讨论】:

以上是关于可以在构造函数中获取值,但是在render函数中输出TypeError: Cannot read property 'xxx' of undefined的主要内容,如果未能解决你的问题,请参考以下文章

Flutter:如何在构造函数中传递值,以便我可以重用我的小部件?

React 之 render props 的理解

Go 中的构造函数

Render() 状态元素最初是空的,直到 api 调用

Java——变量

构造函数主要特点