import React, { Component } from 'react';
import { View, ListView,ToolbarAndroid } from 'react-native';
import ListItem from './components/ListItem';
import styles from './styles';
import * as firebase from 'firebase';
const firebaseConfig = {
apiKey: 'AIzaSyDEvv0loyjX47GXQp1IlHl3MpR7yCc0KDo',
authDomain: 'simple-to-do-b592d.firebaseapp.com',
databaseURL: 'https://simple-to-do-b592d.firebaseio.com',
projectId: 'simple-to-do-b592d',
storageBucket: 'simple-to-do-b592d.appspot.com',
messagingSenderId: '410223452360'
};
// Initialize the firebase app here and pass it to other components as needed. Only initialize on startup.
const firebaseAppx = firebase.initializeApp(firebaseConfig);
export default class App extends Component {
constructor(props) {
super(props);
this.taskRef = firebaseAppx.database().ref();
const dataSource = new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
});
this.state = {
dataSource: dataSource
};
}
componentDidMount() {
// start listening for firebase updates
this.listenForTasks(this.tasksRef);
}
render() {
return (
<View style={styles.container}>
<ToolbarAndroid
style={styles.navbar}
title="Todo List" />
<ListView
enableEmptySections={true}
dataSource={this.state.dataSource}
renderRow={this._renderItem.bind(this)}
style={styles.listView}/>
</View>
);
}
_renderItem(task) {
return (
<ListItem task={task} />
);
}
listenForTasks(tasksRef) {
console.log(tasksRef);
tasksRef.on('value', (dataSnapshot) => {
var tasks = [];
dataSnapshot.forEach((child) => {
tasks.push({
name: child.val().title,
_key: child.key
});
});
this.setState({
dataSource: this.state.dataSource.cloneWithRows(tasks)
});
});
}
}
上面的代码尝试连接到firebase,但我一直在点击TypeError: undefined is not an object (evaluating 'tasksRef.on')
试图控制台记录它,但它的显示确实未定义
答案 0 :(得分:1)
错误就在这里
this.listenForTasks(this.tasksRef);
你需要通过
this.listenForTasks(this.taskRef);
因为您的本地变量名称为taskRef
而非tasksRef