简体   繁体   English

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

[英]How to call one of multiple functions - JavaScript?

I have three functions: 我有三个功能:

  1. Change Email 更改电子邮件
  2. Change password 更改密码
  3. Change 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 和一个按钮来调用它们,当用户更改其数据而不更改电子邮件或密码时,我不会调用其他功能“ 更改电子邮件”或“更改密码”,而只需调用该功能“更改其他数据”,以及使用其他数据(例如用户名)更改其电子邮件时,位置我只想打电话更改电子邮件,更改其他数据功能,更改密码

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? 那么如何处理此问题,以及如何在输入错误密码时更改当前数据并获取其他密码并将其保存在我的状态cuz中?

I'm using Firebase as a backend 我正在使用Firebase作为后端

Edit Screen 编辑画面

编辑画面

here is my code [React Native App] 这是我的代码[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;

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

Option 1 选项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);
  }
}

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

Please do the following: 请执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM