如何调用多种功能之一-JavaScript?

时间:2019-06-12 17:56:15

标签: javascript reactjs react-native asynchronous async-await

我有三个功能:

  1. 更改电子邮件
  2. 更改密码
  3. 更改otherData

和一个按钮来称呼他们, 当用户更改其数据而不更改电子邮件或密码时,我不会调用其他功能更改电子邮件或更改密码,而只需调用该功能更改其他数据,以及使用其他数据(例如用户名)更改电子邮件时,位置我只想打电话更改电子邮件,更改其他数据功能而不是更改密码

那么,当我输入错误的密码时,如何处理此问题以及如何获取当前密码并将其保存在我的状态cuz中,更改执行其他数据功能?

我正在使用Firebase作为后端

编辑屏幕

Edit Screen

这是我的代码 [React Native App]

import React, { Component } from 'react';
import firebase from "react-native-firebase";

import Icon from 'react-native-vector-icons/Ionicons';
import styles from "../Style/styles";

import AsyncStorage from '@react-native-community/async-storage';

import {
    View,
    Text,
    KeyboardAvoidingView,
    StyleSheet,
    ActivityIndicator,
    TouchableOpacity,
    TextInput,
    ScrollView
} from 'react-native';


class profileEdit extends Component {
    constructor(props) {
        super(props);
        this.state = {
            currentPassword: "",
            newPassword: "",
            currentUser: {
                username: "",
                email: "",
                city: "",
                mobileNumber: "",
            },
            data: {},
            loading: true
        }
    }
    async componentDidMount() {
        try {
            const userId = firebase.auth().currentUser.uid;
            await this.setState({ userId });
            console.log("@uid", this.state.userId);
            let recentPostsRef = firebase.database().ref(`users/${userId}`);
            await recentPostsRef.once('value').then(snapshot => {
                this.setState({ currentUser: snapshot.val(), loading: false })
                console.log(this.state.currentUser)
            }).catch((error) => console.log("@error", error));
        } catch (error) {
            console.log("@CError", error);
        }
    }

    reauthenticate = (currentPassword) => {
        var user = firebase.auth().currentUser;
        var cred = firebase.auth.EmailAuthProvider.credential(
            user.email, currentPassword);
        return user.reauthenticateWithCredential(cred);
    }

    _updateProfileData = async () => {
        if (this.state.currentPassword === "") {
            alert("please write your current password first!")
            return;
        } else {
            await this._updateData();
            await this.changeEmail();
            await this.changePassword();
        }
    }
    changePassword = () => {
        if (this.state.currentPassword === "" || this.state.newPassword === "") {
            return
        } else {
            this.reauthenticate(this.state.currentPassword).then(() => {
                var user = firebase.auth().currentUser;
                user.updatePassword(this.state.newPassword).then(() => {
                    console.log("Pssword updated!");
                    this._updateData();
                    this.setState({ newPassword: "", currentPassword: "" });
                }).catch((error) => console.log(error.message));
            }).catch((error) => console.log(error.message));
        }
    }
    changeEmail = () => {
        this.reauthenticate(this.state.currentPassword).then(() => {
            var user = firebase.auth().currentUser;
            user.updateEmail(this.state.currentUser.email).then(() => {
                console.log("Email updated!");
                this._updateData();
            }).catch((error) => { console.log(error) });
        }).catch((error) => { console.log(error) });
    }
    _updateData = () => {
        const { userId, currentUser } = this.state;
        let recentPostsRef = firebase.database().ref(`users/${userId}`);
        recentPostsRef.update({
            username: currentUser.username,
            email: currentUser.email,
            city: currentUser.city,
            mobileNumber: currentUser.mobileNumber,
        }).then(async () => {
            let Data = await AsyncStorage.mergeItem('@MyProfile:data', JSON.stringify(currentUser))
            console.log(Data)
            alert("Great, your profile updated right now!")
        }).then(async () => {
            await AsyncStorage.getItem('@MyProfile:data')
                .then(json => JSON.parse(json))
                .then(currentUser => this.setState({ currentUser }))
                .catch(error => console.log('@error' + error));
        })
    }
    // _logout = () => {
    //     firebase.auth().signOut().then(() => {
    //         alert("Logout successfuly")
    //         setTimeout(() => {
    //             this.props.navigation.navigate("SignIn")
    //         }, 500)
    //     }).catch((error) => console.log("@error", error));
    // }

    render() {
        const { currentUser, loading } = this.state;
        if (loading) {
            return (
                <View style={{ justifyContent: "center", alignItems: "center", flex: 1 }}>
                    <Text>Just a moment.</Text>
                    <ActivityIndicator size="large" color="#1567d3" />
                </View>
            )
        } else {
            console.log("Loading False");
            return (
                <ScrollView scrollEnabled={true}>
                    <KeyboardAvoidingView behavior="padding" keyboardVerticalOffset={70}>
                        <View style={{ flex: 1 }}>
                            <View style={styles.logoSection}>
                                {/* <SvgComponent height={100} /> */}
                                <Icon name="ios-contact" size={90} color='#4d8dd6' style={{ marginTop: 9 }} />

                                <Text style={{ fontSize: 18, color: "#000", margin: 35, marginTop: 7 }}>
                                    {currentUser.username}
                                </Text>
                            </View>

                            {/* //username */}
                            <View style={style.child}>
                                <Icon name="ios-contact" size={30} color='#4285f4' style={{ marginTop: 9 }} />
                                <TextInput
                                    style={style.textInput}
                                    autoCapitalize="words"
                                    value={currentUser.username}
                                    onChangeText={(username) => { this.setState(Object.assign(currentUser, { username: username })) }}
                                />
                            </View>

                            {/* //Email */}
                            <View style={style.child}>
                                <Icon name="md-at" size={30} color='#4285f4' style={{ marginTop: 9 }} />
                                <TextInput
                                    style={style.textInput}
                                    keyboardType="email-address"
                                    autoCapitalize="words"
                                    value={currentUser.email}
                                    onChangeText={
                                        (email) => { this.setState(Object.assign(currentUser, { email: email })) }
                                    }
                                />
                            </View>

                            {/* //Password */}

                            <View style={style.child}>
                                <Icon name="md-lock" size={30} color='#4285f4' style={{ marginTop: 9 }} />
                                <TextInput
                                    style={style.textInput}
                                    autoCapitalize="words"
                                    placeholder="current password"
                                    value={this.state.currentPassword}
                                    onChangeText={(currentPassword) => this.setState({ currentPassword })}
                                />
                            </View>
                            <View style={style.child}>
                                <Icon name="md-lock" size={30} color='#4285f4' style={{ marginTop: 9 }} />
                                <TextInput
                                    style={style.textInput}
                                    autoCapitalize="words"
                                    placeholder="New password"
                                    value={this.state.newPassword}
                                    onChangeText={(newPassword) => { this.setState({ newPassword }) }}
                                />
                            </View>

                            {/* //Location */}
                            <View style={style.child}>
                                <Icon name="ios-navigate" size={30} color='#4285f4' style={{ marginTop: 9 }} />
                                <TextInput
                                    style={style.textInput}
                                    autoCapitalize="words"
                                    placeholder="New City"
                                    value={currentUser.city}
                                    onChangeText={(city) => { this.setState(Object.assign(currentUser, { city: city })) }}
                                />
                            </View>

                            <View style={style.child}>
                                <Icon name="ios-call" size={30} color='#4285f4' style={{ marginTop: 9 }} />
                                <TextInput
                                    style={style.textInput}
                                    autoCapitalize="words"
                                    keyboardType="number-pad"
                                    placeholder="New Mobile Number"
                                    value={currentUser.mobileNumber}
                                    onChangeText={(mobileNumber) => { this.setState(Object.assign(currentUser, { mobileNumber: mobileNumber })) }}
                                />
                            </View>

                            {/* Logout 
                            <TouchableOpacity style={style.logout} onPress={this._logout}>
                                <Icon name="md-power" size={25} color='#0496FF' style={{ marginTop: -2 }} />
                                <Text style={{ paddingLeft: 10 }}>Logout</Text>
                            </TouchableOpacity>
                            */}
                        </View>

                        {/* Save */}
                        <TouchableOpacity onPress={this._updateProfileData}
                            style={[styles.button, style.saveBtn]}>
                            <Text style={styles.TextButton}>Save</Text>
                        </TouchableOpacity>

                    </KeyboardAvoidingView>
                </ScrollView>
            );
        }
    }
}

export default profileEdit;

2 个答案:

答案 0 :(得分:0)

我认为您有两个选择,选择添加更多变量以声明可与之比较的新数据,选择两个使用三个布尔值,一个用于密码,电子邮件等。

选项1

constructor(props) {
  super(props);
  this.state = {
    currentPassword: "",
    newPassword: "",
    email: '',
    currentUser: {
      username: "",
      email: "",
      city: "",
      mobileNumber: "",
    },
    username: '',
    city: '',
    mobileNumber: '',
    data: {},
    loading: true
  }
}

_updateProfileData = async () => {

  const { currentPassword, email, currentUser, newPassword,
    mobileNumber, username, city } = this.state;

  if (currentPassword === "") {
    alert("please write your current password first!")
    return;
  }

  if (email !== currentUser.email) {
    // email changed update
    await this.changeEmail();
  }

  if (newPassword !== currentPassword) {
    // password changed update
    await this.changePassword();
  }

  if (city !== currentUser.city || mobileNumber !== currentUser.mobileNumber || username !== currentUser.username) {
    await this._updateData();
  }
}

async componentDidMount() {
  try {
    const userId = firebase.auth().currentUser.uid;
    await this.setState({ userId });
    console.log("@uid", this.state.userId);
    let recentPostsRef = firebase.database().ref(`users/${userId}`);
    await recentPostsRef.once('value').then(snapshot => {
      const currentUser = snapshot.val();
      this.setState({ currentUser: currentUser, email: currentUser.email, username: currentUser.username, city: currentUser.city, mobileNumber: currentUser.mobileNumber, loading: false })
      console.log(this.state.currentUser)
    }).catch((error) => console.log("@error", error));
  } catch (error) {
    console.log("@CError", error);
  }
}

选项2 ,具有三个布尔值,passwordChanged,emailChanged,otherChanged,当用户键入其中一个输入时,将该值设置为true,然后在_updateProfileData中检查该值是否为true,然后更新值。

constructor(props) {
  super(props);
  this.state = {
    currentPassword: "",
    newPassword: "",
    currentUser: {
      username: "",
      email: "",
      city: "",
      mobileNumber: "",
    },
    data: {},
    // boolean values for email, password and other
    passwordChanged: false,
    emailChanged: false,
    otherChanged: false,
    loading: true
  }
}

_updateProfileData = async () => {

  const { currentPassword, passwordChanged, emailChanged, otherChanged } = this.state;

  if (currentPassword === "") {
    alert("please write your current password first!")
    return;
  }

  if (emailChanged) {
    // email changed update
    await this.changeEmail();
  }

  if (passwordChanged) {
    // password changed update
    await this.changePassword();
  }

  if (otherChanged) {
    await this._updateData();
  }
}

答案 1 :(得分:-2)

请执行以下操作:

// You have to change the method _updateProfileData as following
_updateProfileData = async () => {
        if (this.state.currentPassword === "") {
            alert("please write your current password first!")
            return;
        } if (this.state.currentUser.email === "") {
            alert("Email can't be blank")
            return;
        } if (this.state.currentUser.username === "") {
            alert("Username can't be blank")
            return;
        } if (this.state.currentUser.city === "") {
            alert("City can't be blank")
            return;
        } if (this.state.currentUser.mobileNumber === "") {
            alert("Mobile number can't be blank")
            return;
        } else {
            this._getCurrentUserData((oldUserData) => {
            if(oldUserData.email !== this.state.currentUser.email) {
                 await this.changeEmail();
            }

            if(this.state.newPassword !== this.state.currentPassword) {
                 await this.changePassword();
            }

            if(oldUserData.username !== this.state.currentUser.username || oldUserData.city !== this.state.currentUser.city || oldUserData.mobileNumber !== this.state.currentUser.mobileNumber ) {
                 await this._updateData();
            }
            );
        }
    }

// You have to add this method in your component
_getCurrentUserData = (callBack) => {
   AsyncStorage.getItem('@MyProfile:data')
            .then(json => JSON.parse(json))
            .then(currentUser => callBack(currentUser))
            .catch(error => console.log('@error' + error));
}