【发布时间】:2020-08-21 11:22:36
【问题描述】:
我有一个发送电子邮件的功能。但是 setLoading、setLoading1 的状态没有更新。最初,两个加载都设置为 false。控制台 console.log("no",loading,loading1); 返回 no false false 和控制台 console.log("load",loadingState) em> 返回负载错误。 所有其他功能都正常工作。
async function submitEmail(pr) {
let complete = await errorMessageHandler();
if (complete == "") {
if (pr == "No") {
let loadingState = loading;
console.log("load", loadingState)
await setLoading(!loadingState);
} else {
await setLoading1(true)
}
console.log("no", loading, loading1);
RNSmtpMailer.sendMail({
mailhost: "mail.oscon.net",
port: "465",
ssl: true,
username: "**********",
password: "********",
from: "**********",
recipients: "************",
subject: "New Registration From Mobile app",
htmlBody: emailContent(pr),
attachmentPaths: [],
attachmentNames: [],
})
.then(success => {
setLoading(false);
setLoading1(false);
})
.catch(err => {
setLoading(false);
setLoading1(false);
});
}
}
我该如何解决这个问题?
【问题讨论】:
-
请用minimal reproducible example 更新您的问题来证明问题,最好是使用堆栈片段(
[<>]工具栏按钮)可运行。 Stack Snippets 支持 React,包括 JSX; here's how to do one。 (因为这是一个关于 React 状态的问题,所以您使用 React Native 的事实并不一定会阻止您使用 React 创建 MRE。) -
假设
setLoading和setLoading1是状态设置器(例如,来自useState),它们不会返回承诺,而await发送它们是毫无意义的。除此之外,以上内容并没有为我们提供足够的背景来真正提供帮助。 -
展示你实现钩子的方式可能有助于我们找出问题所在,在此之前你可以尝试移动 console.log("no",loading,loading1);在 .then() 中确保它没有在等待解析的 setState 之前执行,而 console.log 不是。
-
const[loading,setLoading]=useState(false);常量 [loading1,setLoading1]=useState(false);这就是如何定义我的状态。没有用将控制台放在 .then() 语句中
标签: javascript reactjs react-native react-hooks