这让我感到困惑,为什么我不能从状态中获取数据,我已经尝试了很多事情,但是没有运气。
我正在从Firebase数据库获取数据,并且试图将数据存储到状态中,然后可以从该状态访问该数据。
任何建议将不胜感激。
谢谢
state = {
isDateTimePickerVisible: false,
mode: "time",
minuteInterval: 30,
selectedDate: {},
isLoading: true,
syllabus: [{value: 'Banana'}],
users: [{
value: 'Banana',
app_id: 'apple',
}],
timeSlots:[{
name: 'test',
time: '123',
}],
};
testStore() {
let returnArr = [];
db.ref('bookings/' + this.user).child("22-09-2018").once('value').then(function(snapshot) {
let data = snapshot.val();
let timeSlot = Object.values(data);
console.log("testStore: " + timeSlot[0].name);
//gets data from the firebase database -- testStore: james
dt = timeSlot;
this.setState({
timeSlots: dt
});
}.bind(this));
this.testState();
}
testState() {
console.log("test state " + this.state.timeSlots[0].name);
//Get A red screen with error undefined is not an object(evaluating 'this.state.timeSlots['name'])
}
onDayPress(day) {
console.log("day press " + day.dateString);
this.testStore();
var st = day.dateString;
var dt = new Date(st);
var today = dt;
var dd = today.getDate();
var mm = today.getMonth() + 1; //January is 0!
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
var today = dd + '-' + mm + '-' + yyyy;
console.log("date is " + today);
this.setState({
selectedDate: today
});
}
答案 0 :(得分:1)
从完整的代码来看,似乎您的构造函数正在将您的状态重写为空对象(因此this.state.timeSlots[0].name
确实是有问题的)
我将您的构造函数重写为:
constructor(props) {
super(props)
this.state = {
isDateTimePickerVisible: false,
mode: 'time',
minuteInterval: 30,
selectedDate: {},
isLoading: true,
syllabus: [{
value: 'Banana',
}],
users: [{
value: 'Banana',
app_id: 'apple',
}],
slots: [{
name: 'test',
time: '123',
user_id: '373737',
}],
}
this.onDayPress = this.onDayPress.bind(this)
this.testStore = this.testStore.bind(this)
}
和testStore为:
testStore() {
const returnArr = []
db.ref(`bookings/${this.user}`).child('22-09-2018').once('value').then((snapshot) => {
const data = snapshot.val()
const timeSlot = Object.values(data)
console.log(`testStore: ${timeSlot[0].name}`)
dt = timeSlot
this.setState({
timeSlots: dt
}, () => {
console.log('after setState', this.state.timeSlots)
})
})
}