首页 > 解决方案 > 使用函数内的箭头函数更改父状态

问题描述

我有一个注册用户功能,如下所示:

  onRegisterUser = () => {
    const { email, password, isLoading} = this.state;
    const { navigation } = this.props;
    registerUser(
      email,
      password,
      () =>
        this.setState({
          isLoading: !this.state.isLoading,
        }),
      navigation
    );
  };

该函数从注册屏幕接收输入电子邮件、传递和 isLoading 状态,并执行以下操作:

import { Alert } from "react-native";
import firebase from "./firebase";
import { newUser } from "./database";

export const registerUser = (email, password, toggleLoading) => {
  toggleLoading();

  const isInputBlank = !email || !password;
  if (isInputBlank) {
    Alert.alert("Enter details to signup!");
    toggleLoading();
  }
  //If Everything OK Register User
  else {
    //CR: change to async-await
    firebase
      .auth()
      .createUserWithEmailAndPassword(email, password)
      .then(() => {
        newUser(firebase.auth().currentUser.uid);
      })
      .catch(function (error) {
        // Handle Errors here.

        var errorCode = error.code;
        var errorMessage = error.message;
        if (errorCode == "auth/weak-password") {
          alert("The password is too weak.");
        } else if (errorCode == "auth/invalid-email") {
          alert("Email is Invalid");
        } else if (errorCode == "auth/email-already-in-use") {
          alert("Email is Already in use!");
        } else {
          alert(errorMessage);
        }
        console.log(error);
      });
  }
};

我的问题是toggleLoading();Insideif (isInputBlank)没有做任何事情,如果我收到错误(本例中为空输入),我试图更改 isLoading 状态,但它什么也没做,它在开始时只工作一次,就是这样。如果警报在我关闭时被激活,加载屏幕仍然存在

我错过了什么?

标签: reactjsreact-native

解决方案


像这样链接到原始承诺不是更好吗:

 export const registerUser = (email, password) => {
  if (!email && ! password) { 
   return Promise.reject('Email and Password required'); // or whatever message you like to display
  }
  
  return (
    yourCallToFirebase()
     .then(() => newUser())
     .catch(() => {
       let errorMessage;
       // your error handling logic
       return Promise.reject(errorMessage);
     })
  )
 };

用法

onRegisterUser = () => {
 const { email, password, isLoading} = this.state;
 const { navigation } = this.props;
 this.setState({ isLoading: true })
 registerUser(email,password)
  .then(() => {
   // your logic when user gets authenticated (ex. navigate to a route)
  })
  .catch((errorMessage) => { 
   // display feedback (like a toast)
  })
  .finall(() => this.setState({ isLoading: false }));
};

推荐阅读