reactjs - 使用函数内的箭头函数更改父状态
问题描述
我有一个注册用户功能,如下所示:
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 状态,但它什么也没做,它在开始时只工作一次,就是这样。如果警报在我关闭时被激活,加载屏幕仍然存在
我错过了什么?
解决方案
像这样链接到原始承诺不是更好吗:
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 }));
};
推荐阅读
- javascript - 使用 match 按指定时区的日期查找文档
- javascript - laravel中的js问题
- objective-c - NSScrollView setMagnification:centeredAtPoint:一个可能的错误?
- java - 如何在Java中显示这样的输出(条件:可以输入的元素最多10个)(图像)
- c# - 来自时间戳服务器的签名 pdf 缺少时间戳
- exception - UnauthorizedAccessException:对路径“D:\”的访问被拒绝
- java - LocalDateTime.toString - 可以在环境中配置格式吗?
- python-3.x - 我正在尝试构建一个简单的 webscraper 并不断收到此 SSL 错误:
- markdown - 如何为使用 Mkdocs 生成的一组 html 页面实现一个好的搜索系统?
- reactjs - Redux 等待调度和处理错误