React Usestate中的布尔人被铸成相反的价值
在使用Firebase Auth时创建自己的注册挂钩时,我遇到了一个奇怪的问题。
export const useSignup = () => {
const [error, setError] = useState(null);
const [isPending, setIsPending] = useState(false);
const [isFulfilled, setIsFulfilled] = useState(false);
const { dispatch } = useAuthContext();
const signup = async (email, password) => {
setError(null);
setIsPending(true);
try {
const res = await projectAuth.createUserWithEmailAndPassword(
email,
password
);
if (!res) {
throw new Error('Sign up has failed, please try again.');
}
dispatch({ type: 'LOGIN', payload: res.user });
// Will be casted as 'true', no idea why
setIsFulfilled(false);
if (!isCancelled) {
setIsPending(false);
setError(null);
}
} catch (err) {
if (!isCancelled) {
setError(err.message);
setIsPending(false);
// Will be casted as 'false', also no idea why
setIsFulfilled(true);
}
}
};
return { signup, error, isPending, isFulfilled };
};
注册过程将完成后,我想将的状态设置为iSfulfill
true
,然后将其转发,但奇怪的是,在调试和将其记录到控制台时,它输出false ,即使我在调用
setIsfulfill(true)
后立即检查它。
什么干扰状态,因此输出相反的布尔值?
During creating my own sign up hook while using Firebase Auth, I've encountered a strange issue.
export const useSignup = () => {
const [error, setError] = useState(null);
const [isPending, setIsPending] = useState(false);
const [isFulfilled, setIsFulfilled] = useState(false);
const { dispatch } = useAuthContext();
const signup = async (email, password) => {
setError(null);
setIsPending(true);
try {
const res = await projectAuth.createUserWithEmailAndPassword(
email,
password
);
if (!res) {
throw new Error('Sign up has failed, please try again.');
}
dispatch({ type: 'LOGIN', payload: res.user });
// Will be casted as 'true', no idea why
setIsFulfilled(false);
if (!isCancelled) {
setIsPending(false);
setError(null);
}
} catch (err) {
if (!isCancelled) {
setError(err.message);
setIsPending(false);
// Will be casted as 'false', also no idea why
setIsFulfilled(true);
}
}
};
return { signup, error, isPending, isFulfilled };
};
After registration process will be complete, I want to set state of isFulfilled
to true
and pass it forward, but strangely, while debugging and logging it to console, it outputs false
, even if I check it immediately after invoking setIsFulfilled(true)
.
What interferes with state, so it outputs a contrary Boolean values?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请记住,设置状态(即,使用
streispending
)时,这是一个异步的呼叫,因此,请不要期望它们在没有各自的等待的情况下行动同步。另外,也许使用使用
在您的实现方面可能很有用remember that when setting states (ie, when using
setIsPending
) it's an asynchronous call, so don't expect them to act synchronous without their respective awaits. also, perhaps the use ofuseEffect
might be useful looking at your implementation