我的数组不是空的,而是 array.length returns 0

My array is not empty but array.length returns 0

这是我今天一直在尝试调试的一个非常奇怪的问题; 当组件安装时,我会收到通知以像这样显示它们

  componentDidMount() {
    this.setState(
      {
        notifications: this.props.notifications,
      }
    );
  }

然后我尝试通过添加这个

来控制台记录通知
  componentDidMount() {
    this.setState(
      {
        notifications: this.props.notifications,
      },
      () => {
        console.log(this.state.notifications);
        console.log(this.state.notifications.length);
      }
    );
  }

我得到的是这个!

首先console.log()

[]
0: {title: "Success", text: "You have successfully created a new game!", destination: {…}, type: "GameCreated"}
length: 1
__proto__: Array(0)

秒console.log()

0

数组长度不应该是1而不是0吗?我在那个数组中确实有一个元素。 此外,当我尝试获取该数组的第一个值时,它 returns undefined.

感谢您花时间阅读本文并提供帮助!

当您输出具有 console.log 的对象时,它的状态可能会发生变化,您不一定会在调用 console.log 时看到该对象的状态,而只能在它展开时看到控制台视图。原语不是这种情况。 最可能的情况:当调用 console.log 时,数组为空,长度为 0。当您在控制台视图中展开数组日志时,您会看到它已填充,即使它不是在记录时。

我做了同样的测试,它在我的电脑上运行正常,它记录长度为 1。 也许您的代码中还有其他东西导致了副作用

在您的浏览器中,console.log 作为异步函数工作。

检查这个问题:Is Chrome's JavaScript console lazy about evaluating arrays?

为避免这种情况,您可以像下面这样使用 JOSN.parse( JSON.stringify(MutableData) )

componentDidMount() {
    this.setState(
      {
        notifications: this.props.notifications,
      },
      () => {
        console.log(JSON.parse(JSON.stringify(this.state.notifications)));
        console.log(this.state.notifications.length);
      }
    );
  }