【问题标题】:React cannot set state of react HooksReact 无法设置 React Hooks 的状态
【发布时间】: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


【解决方案1】:

setState 是一种异步操作,但它不返回 Promise,所以等待它们是没有意义的,代码如下:

const [myState, setMyState] = useState(false)
setMyState(true)
console.log(myState)

只是将你想要改变状态的愿望发送到 React,但实际上并没有改变它,不管你是否在这里使用 async-await。控制台日志会显示初始值,因为它是主调用堆栈的一部分,而不是异步操作。

如果您想捕捉状态更改的时刻,请使用 ComponentDidUpdate 用于基于类的组件或 useEffect 挂钩用于功能组件。

const [myState, setMyState] = useState(false)
...
useEffect(()=>{
  console.log(myState) // show when myState is changed
}, [myState])

【讨论】:

  • 谢谢。您的内容帮助我解决了问题。
猜你喜欢
  • 1970-01-01
  • 2020-11-02
  • 2020-01-15
  • 2021-02-28
  • 2023-04-04
  • 1970-01-01
  • 2019-11-01
  • 1970-01-01
  • 2021-06-03
相关资源
最近更新 更多