TypeError: undefined is not an object (evalating...)

问题描述 投票:0回答:1

在render()之前的控制台中,this.state.data1.length没有出现任何错误,但是当我在视图标签中使用它时,它就会出现错误,如.typeError: undefined is not an object (evalating '_this.state.data1.length')。TypeError: undefined is not an object (evalating '_this.state.data1.length')如果我从视图标签中删除这一行,那么在我的reacttable标签中就不会有任何打印,因此我想这一行是需要的,但是我应该做什么改变,以便在使用react native代码时不会出现错误,并且我的检索数据也会打印在我的应用程序中。

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 }
});
firebase react-native react-table data-retrieval
1个回答
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>
    );
}
}

enter image description here

希望能帮到你!


0
投票

你唯一的问题是,使用了 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 },
});

© www.soinside.com 2019 - 2024. All rights reserved.