开发者问题收集

如何将选定的日期对象从 datetimepicker 存储到 firebase 并进行检索?

2020-05-25
961

这是分别从 firebase 发送和接收数据的代码。

class Fire {
    addAppointment(currentDate, addComplete) {
            firebase.firestore()
                .collection("appointment")
                .add({
                    date: currentDate.date,
                    createdAt: firebase.firestore.FieldValue.serverTimestamp()
                }).then((snapshot) => snapshot.get())
                .then((dateInfo) => addComplete(dateInfo.data()))
                .catch((error) => alert(error));
        }

        getAppointment = async ({ dateRetreived }) => {
            var dateList = [];

            var snapshot = await firebase.firestore()
                .collection("appointment")
                .orderBy('createdAt')
                .get()

            snapshot.forEach((doc) => {
                const dateCreated = doc.data();
                dateCreated.id = doc.id;
                dateList.push(dateCreated);
            });

            dateRetreived(dateList);
        }
}

Fire.shared = new Fire();
export default Fire;

这是将“currentDate”发送到上面代码的 datetimepicker 代码。请注意,onChange 已更改为 handleChange。

class Booking extends Component {
    state = {
        isDatePickerVisible: false,
        date: new Date(),

    };

    showDateTimePicker = () => {
        this.setState({
            isDatePickerVisible: true
        })
    }

    hideDateTimePicker = () => {
        this.setState({
            isDatePickerVisible: false
        })
    }

    handleChange = (event, selectedDate) => {
        const currentDate = selectedDate || date;
        this.setState(prevState => ({
            currentDate: prevState.currentDate = currentDate
          }));
      };


    render() {
        return (
            <View>

                <View style={styles.picker}>
                    <Button
                        title="Show Date Picker" onPress={this.showDateTimePicker}
                    />
                    <DateTimePicker
                        cancelTextIOS={'Exit'}
                        confirmTextIOS={'OK'}
                        isVisible={this.state.isDatePickerVisible}
                        mode="date"
                        onConfirm={this.handleChange}
                        onCancel={this.hideDateTimePicker} 
                        is24Hour={false} 
                    />
                </View>

                <View style={styles.btn} >
                    <Button
                        onPress={() =>
                            Fire.shared.addAppointment(this.handleChange)
                        }
                        title="Book"
                    />
                </View>
            </View>

        )
    };
};

export default Booking;

我收到一条错误消息:

FirebaseError: function documentReference.set() called with invalid data. unsupported field value: undefined (found in field date)

我对代码做了一些更改:

addAppointment(currentDate, addComplete) {
        firebase.firestore()
            .collection("appointment")
            .add({
                date: firebase.firestore.Timestamp.fromDate(new Date(currentDate)),
             ...
    }  

AND On state:

   state = {
            isDatePickerVisible: false,
            Date: new Date(1598051730000),

        };

On processing change

  handleChange = (event, selectedDate) => {
            const currentDate = selectedDate || Date;
            this.setState(prevState => ({
                currentDate: prevState.currentDate = currentDate
              }));
          };

On DateTimePicker

onConfirm={this.handleChange}

On Book button

<Button onPress={() => {Fire.shared.addAppointment(this.handleChange)}}
                        title="Book"
                    />

选择日期后,我没有收到 ReferenceError: date is not defined 。当我按下 BOOK 时,没有发生任何错误,Cloud Firestore 中也没有显示任何数据。

2个回答

由于您将 Date 存储在您的州中,因此无需将其作为参数传递。只需直接访问它:

<Button onPress={() => {Fire.shared.addAppointment(this.onChange)}} title="Book" />
addAppointment(addComplete) {
  firebase
    .firestore()
    .collection("appointment")
    .add({
      date: this.state.currentDate.date,
      createdAt: firebase.firestore.FieldValue.serverTimestamp(),
    })
    .then((snapshot) => snapshot.get())
    .then((dateInfo) => addComplete(dateInfo.data()))
    .catch((error) => alert(error));
}

Yogesh Aggarwal
2020-05-26

经过一番努力,我终于将 addAppointment 方法引入了 DatePicker.js 文件。这对我来说很有效。

const Booking = () => {
    const [date, setDate] = useState(new Date());
    const [mode, setMode] = useState('date');
    const [show, setShow] = useState(false);

    const showMode = currentMode => {
        setShow(true);
        setMode(currentMode);
    };

    const showDatepicker = () => {
        showMode('date');
    };

    const showTimepicker = () => {
        showMode('time');
    };

    const onChange = (event, date) => {
        const currentDate = date;
        setShow(Platform.OS === 'ios');
        setDate(currentDate);
        console.warn(currentDate);
    };

    const addAppointment = () => {
        firebase.firestore()
            .collection("appointment")
            .add({
                uid: firebase.auth().currentUser.uid,
                date: firebase.firestore.Timestamp.fromDate(date),
                createdAt: firebase.firestore.FieldValue.serverTimestamp()
            }).then((snapshot) => snapshot.get())
            .catch((error) => alert(error));
    }

    return (
        <View>
            <View>

                <View style={styles.picker}>
                    <Button onPress={showDatepicker} title="Show date picker!" />
                </View>
                <View style={styles.picker}>
                    <Button onPress={showTimepicker} title="Show time picker!" />
                </View>
                {show && (
                    <DateTimePicker
                        testID="dateTimePicker"
                        timeZoneOffsetInMinutes={0}
                        value={date}
                        mode={mode}
                        is24Hour={true}
                        display="default"
                        onChange={onChange}
                    />
                )}
            </View>

            <View style={styles.btn} >
                <Button
                    onPress={() => addAppointment(onChange)}
                    title="Book"
                />
            </View>
        </View >

    );
};

export default Booking;
B_M
2020-06-02