为什么在异步函数中不更新反应钩子值? [英] Why react hook value is not updated in async function?

查看:30
本文介绍了为什么在异步函数中不更新反应钩子值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在运行 run 函数时,我希望 value 变量的值为new",但即使 500 毫秒,它仍然保持旧"状态.为什么会发生这种情况,如何解决这个问题?

When running the run function, I expect that value variable has value 'new', but since even 500 ms, it still remains 'old'. Why that happens and how coud this issue be solved?

import React, { Component, useState } from "react";
import { render } from "react-dom";

function App() {
  const [value, setValue] = useState('old');

  const run = async() => {
    setValue('new')
    const data = await wait(500)
    console.log(value)
  }

  return (
    <button onClick={run}>
      Run
    </button>
  );
}

render(<App />, document.getElementById("root"));

function wait(ms) {
  return new Promise(resolve => setTimeout(resolve, ms))
}

推荐答案

setState 异步运行,因此它不会立即反映在功能代码块中.您可以尝试使用 useEffect 来观察您的状态变化.

setState runs asynchronously so it is not immediately reflected in the function code block. You can try using useEffect to watch changes of your state.

useEffect(() => console.log('value', value), [value])

这篇关于为什么在异步函数中不更新反应钩子值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆