【问题标题】:My array is not empty but array.length returns 0我的数组不为空,但 array.length 返回 0
【发布时间】:2020-07-19 17:11:06
【问题描述】:

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

  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吗?我确实在该数组中有一个元素。 此外,当我尝试获取该数组的第一个值时,它返回未定义。

感谢您抽出宝贵时间阅读本文并提供帮助!

【问题讨论】:

  • useState 本质上是异步的。所以如果你在它设置状态之前尝试访问它,它会报错
  • 请通过将屏幕截图替换为文本(复制和粘贴)来编辑您的问题。链接不仅会消失,还会给视障人士带来问题。
  • @RamblinRose 我更新了它 :) 抱歉!

标签: node.js reactjs mern


【解决方案1】:

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

【讨论】:

  • 要验证这一点,您可以将这一行更改为console.log([ ...this.state.notifications ]),这样记录的对象在您能够检查之前不会发生变异
  • 这实际上是非常正确的,我确实用你提到的内容更改了我的控制台日志,它也返回了一个空数组。谢谢!
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    在您的浏览器中,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);
          }
        );
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-08
      • 2018-01-30
      • 2020-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多