简体   繁体   English

在控制台日志中第一次单击时,react js useState 数组为空

[英]react js useState array is empty in first time click in the console log

Please check my below code.请检查我下面的代码。 I try to check the console log value, but in the first button click, the array is empty.我尝试检查控制台日志值,但在第一次单击按钮时,数组为空。 After the second click the array will be loaded correctly.第二次单击后,阵列将正确加载。

Please check this:请检查这个:

sample 样本

The above sample can be found on Google.上面的示例可以在谷歌上找到。 I console log the value as below我控制台记录的值如下在此处输入图片说明

Why is the array empty in the first click?为什么第一次点击数组为空? Another question is, I need to print the value in the first click.另一个问题是,我需要在第一次点击时打印值。 How can I do it?我该怎么做? Do you know any alternative method?你知道任何替代方法吗?

It's not empty on the first click but you can handle it this way :第一次点击时它不是空的,但你可以这样处理:

const addItem = () => {
    setItem([
      ...items,
      {
        id: items.length,
        value: Math.floor(Math.random() * 10) + 1
      }
    ]);
  };

  React.useEffect(() => {
    console.log(items);
  }, [items]);

The useEffect hook will console log items after they've been changed so you will see the latest state or in other words the updated and final state . useEffect 钩子将在更改后控制台日志项,因此您将看到最新状态,或者换句话说,更新状态和最终状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM