如何调用多种功能之一-JavaScript? [英] How to call one of multiple functions - JavaScript?

查看:53
本文介绍了如何调用多种功能之一-JavaScript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个功能:

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

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

And One Button to call them , when the user changes his data without change Email Or Password I don't wont to call other function Change Email or Change Password just call the function Change other data, and when changing his email with other data like username, location I just want to call Change Email, change other data Function NOT Change Password

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

So how to handle this, and how to get a current password and save them in my state cuz when I wrote the wrong password, change Other Data function execute?

我正在使用Firebase作为后端

I'm using Firebase as a backend

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;

推荐答案

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

I think you have two options, option add more variables to state which you can use to compare the new data with and option two use three boolean values, one for password, email and other.

选项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,然后进行更新值.

Option 2, have three booleans, passwordChanged,emailChanged,otherChanged when the user types in one of the inputs, set the value to true and in your _updateProfileData check if the value is true, then update the value.

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();
  }
}

这篇关于如何调用多种功能之一-JavaScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆