【问题标题】:TypeError: undefined is not an object (evaluating..)TypeError: undefined is not an object (evalating..)
【发布时间】:2020-08-15 15:02:00
【问题描述】:

在 render() 之前的控制台中 this.state.data1.length 没有给出任何错误,但是一旦我在视图标签中使用它,就会给出错误: TypeError:未定义不是对象(评估'_this.state.data1.length') 如果我从视图标记中删除此行,则我的 reacttable 标记中不会打印任何内容,因此我认为此行是必需的,但我应该进行哪些更改,以便使用 react 本机代码没有错误,并且我检索到的数据也打印在我的应用程序上。

import React, { Component } from 'react';
import { StyleSheet, View, Text, Button } from 'react-native';
import ReactTable from 'react-table';
import firebase from 'firebase';

const firebaseConfig = {
...
};
firebase.initializeApp(firebaseConfig);


export default class Form1 extends Component {
constructor(props) {
    super(props);

    this.state = {
        data: [],
        columns: [
            {
                Header: "email",
                accessor: "email"
            },
            {
                Header: "password",
                accessor: "password"
            }
        ]
    }
}

componentDidMount() {
    const data = [];
    const data1 = [];
    var query = firebase.database().ref("/users");
    query.once("value").then((snapshot) => {
      //console.log(snapshot)
        snapshot.forEach((childSnapshot, index) => {

            let singleObj = {
                email: childSnapshot.val().email,
                password: childSnapshot.val().password,
            }

           // console.log('email:',data)
            data.push(singleObj);
           this.setState({data1 : data});
          console.log('sssssssssssssssssss',this.state.data1)
        });
    });
}

submit1=()=>{
console.log(this.state.data1.length)
console.log('data1:',this.state.data1)
}

render() {
    return (
        <View style="styles.container">

            {this.state.data1.length > 0 && <ReactTable data={this.state.data1} columns={this.state.columns} />}
                       <Button title='Submit' onPress={this.submit1.bind(this)} />

        </View>
    );
}
}

const styles = StyleSheet.create({
container: { flex: 1, padding: 16, paddingTop: 30, backgroundColor: '#fff' },
head: { height: 40, backgroundColor: '#f1f8ff' },
text: { margin: 6 }
});

【问题讨论】:

  • 您收到此错误是因为您的组件在数据更新之前正在渲染
  • 那么根据您的说法,我应该进行哪些更改才能获得正确的输出? @user12129132
  • 您没有声明任何状态数据1 将其更改为 this.state.data.length 您是否在这里获得了正确的数据 console.log('sssssssssssssssss',this.state.data1)
  • 是的,在 console.log('sssssssssssssssss',this.state.data1) 中给了我正确的输出。只有在视图标签@user12129132 中使用时才会出错
  • this.state = { data: [],是data1还是data

标签: firebase react-native react-table data-retrieval


【解决方案1】:

像这样更改你的代码:

import React, { Component } from 'react';
import { StyleSheet, View, Text, Button } from 'react-native';
import { Table, Row, Rows } from 'react-native-table-component';


export default class Form1 extends Component {
constructor(props) {
    super(props);

    this.state = {
        data: [],
        tableHead: ['Emails', 'Password'],
        tableData1:[],
    }
}


componentDidMount() {
    var query = firebase.database().ref("/users");
    query.once("value").then((snapshot) => {
        snapshot.forEach((childSnapshot, index) => {
            let singleObj = {
                email: childSnapshot.val().email,
                password: childSnapshot.val().password,
            }
           this.state.data.push(singleObj);
           this.setState({data: this.state.data});
          console.log('sssssssssssssssssss',this.state.data)
        });
        for (var i = 0; i < this.state.data.length; i++) {
            this.state.tableData1[i] = [this.state.data[i].email, this.state.data[i].password];
            this.setState({ tableData1: this.state.tableData1 });
        }

    });
}

submit1=()=>{
console.log(this.state.data.length)
console.log('data1:',this.state.data)
}

render() {
    return (
        <View style={{flex:1,marginTop:100}}>
        {this.state.data.length > 0 &&   
        <Table borderStyle={{borderWidth: 2, borderColor: '#c8e1ff'}}>
        <Row data={this.state.tableHead} />
        <Rows data={this.state.tableData1} />
        </Table>}
      <Button title='Submit' onPress={this.submit1.bind(this)} />

    </View>
    );
}
}

【讨论】:

  • 是的,它仍然显示错误!但错误是不同的。错误是:错误:元素类型无效预期字符串(对于内置组件)或类/函数(对于复合元素),但您未定义。您可能忘记从定义组件的文件中导出组件,或者您可能混淆了默认值和命名导入
  • 修改此代码后显示错误为:必须在 组件中呈现文本字符串
  • {this.state.data[0].email} 这行有效,但它只显示第一个条目的电子邮件,而不是显示整个数据库条目,也没有以表格格式打印
  • 但是为什么只打印数据库的第一个条目?
  • 是的,我明白了,但是当我执行 {this.state.data.email} 时,屏幕上会出现空白
【解决方案2】:

您唯一的问题是,在状态中使用data: [] 而不是data1: []。但是我在您的代码中发现了更多增强功能,以下是我的建议

问题:

1) data1 在渲染时使用但未在状态中初始化

2) 样式对象被用作字符串而不是对象

3) 不是问题,但您不需要绑定_submit,因为它已经是一个箭头函数

import React, { Component } from 'react';
import { StyleSheet, View, Button } from 'react-native';
import ReactTable from 'react-table';
import firebase from 'firebase';

const firebaseConfig = {};
firebase.initializeApp(firebaseConfig);

const COLUMNS = [
  {
    Header: 'email',
    accessor: 'email',
  },
  {
    Header: 'password',
    accessor: 'password',
  },
];

export default class Form1 extends Component {
  state = {
    data: [],
    columns: COLUMNS,
  };

  componentDidMount() {
    const data = [];
    const query = firebase.database().ref('/users');

    query.once('value').then(snapshot => {
      snapshot.forEach((childSnapshot, index) => {
        const singleObj = {
          email: childSnapshot.val().email,
          password: childSnapshot.val().password,
        };

        data.push(singleObj);
        this.setState({ data });
      });
    });
  }

  _submit = () => {
    console.log('data1:', this.state.data);
  }

  render() {
    const { data, columns } = this.state;

    return (
      <View style={styles.container}>
        {data.length > 0 && <ReactTable data={data} columns={columns} />}
        <Button title="Submit" onPress={this._submit} />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: { flex: 1, padding: 16, paddingTop: 30, backgroundColor: '#fff' },
  head: { height: 40, backgroundColor: '#f1f8ff' },
  text: { margin: 6 },
});

【讨论】:

  • 此代码显示的错误与之前的代码显示为错误:元素类型无效预期字符串(用于内置组件)或类/函数(用于复合元素)但您未定义.您可能忘记从定义它的文件中导出组件,或者您可能混淆了默认值和命名导入。但以前的解决方案提供了完美的解决方案
  • @VibhutiBheda 我在上面的代码中没有看到任何问题。介意分享一下你是如何使用它或导入它的吗?
  • 感谢您的帮助,我的错误已提前解决。 :) 非常感谢@Milind Agrawal
【解决方案3】:

首先导入下面一行

import { initializeApp, getApps } from 'firebase/app';

// your config from firebase

const firebaseConfig = {

    apiKey: "AIzaSy****************************",
    authDomain: "i*****dev-a67ad.firebaseapp.com",
    projectId: "i*****dev-a67ad",
    storageBucket: "i*****dev-a67ad.appspot.com",
    messagingSenderId: "1********7930",
    appId: "1:1081248747930:web:5a27b7c60397720d0c2a23",
    measurementId: "G-KDHB8SLTEZ"
  };

// check if app is initialized or not That's it.

if (getApps.length === 0) {
  initializeApp(firebaseConfig);
}

【讨论】:

    猜你喜欢
    • 2019-01-20
    • 1970-01-01
    • 2016-07-30
    • 2020-08-31
    • 2020-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多