【发布时间】: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 我更新了它 :) 抱歉!