【发布时间】:2017-10-20 00:55:43
【问题描述】:
我需要为 Flatlist 中选择的项目更新 Firebase 中的“状态”字段。选择项目时,会出现一个弹出窗口,用户可以选择“完成?”或“失败?”。当代码运行“goalComplete”和“goalFailed”函数时会发生错误,因为 Firebase 引用无法连接到正确的路径。 'onRenderItem' 函数在 'item.key' 上打印正确的键。
错误是“无法读取未定义的'key'的属性”,当'goalComplete'或'goalFailed'运行时发生。
'goal' 和 'status' 字段是使用 .push 函数放入 Firebase 的,该函数会生成我试图在 Firebase 路径中引用的密钥,每一个都比“goal”和“status”高一级项目。
非常感谢您的帮助。
import React, { Component } from 'react';
import { Text, FlatList, View, Image, TouchableOpacity, Alert } from 'react-native';
import firebase from 'firebase';
import { Button, Card, CardSection } from '../common';
import styles from '../Styles';
class List extends Component {
static navigationOptions = {
title: 'List',
}
constructor(props) {
super(props);
this.state = {
goallist: '',
loading: false,
};
}
componentDidMount() {
this.setState({ loading: true });
const { currentUser } = firebase.auth();
const keyParent = firebase.database().ref(`/users/${currentUser.uid}/goalProfile`);
keyParent.on(('child_added'), snapshot => {
const newChild = {
key: snapshot.key,
goal: snapshot.val().goal,
status: snapshot.val().status
};
this.setState((prevState) => ({ goallist: [...prevState.goallist, newChild] }));
console.log(this.state.goallist);
});
this.setState({ loading: false });
}
onRenderItem = ({ item }) => (
<TouchableOpacity onPress={this.showAlert}>
<Text style={styles.listStyle}>
{ item.goal } { item.key }
</Text>
</TouchableOpacity>
);
goalComplete = ({ item }) => {
const { currentUser } = firebase.auth();
firebase.database().ref(`/users/${currentUser.uid}/goalProfile/${item.key}`).update({
status: 'Done'
});//this is not updating status in Firebase for the item selected (get 'key is undefined)'
}
goalFailed = ({ item }) => {
const { currentUser } = firebase.auth();
firebase.database().ref(`/users/${currentUser.uid}/goalProfile/${item.key}`).update({
status: 'Fail'
});//this is not updating status in Firebase for the item selected (get 'key is undefined)'
}
showAlert = () => {
Alert.alert(
'Did you succeed or fail?',
'Update your status',
[
{ text: 'Completed?',
onPress: this.goalComplete
},
{ text: 'Failed?',
onPress: this.goalFailed
},
{ text: 'Cancel',
onPress: () => console.log('Cancel Pressed'),
style: 'cancel' },
],
{ cancelable: false }
);
}
keyExtractor = (item) => item.key;
render() {
return (
<Card>
<View style={{ flex: 1 }}>
<FlatList
data={this.state.goallist}
keyExtractor={this.keyExtractor}
extraData={this.state}
renderItem={this.onRenderItem}
/>
</View>
</Card>
);
}
}
export { List };
【问题讨论】:
标签: javascript firebase react-native firebase-realtime-database