首页 > 解决方案 > 在 react 中访问 this,然后 this.props 将 props 转换为空对象

问题描述

我在 componentDidMount() 中使用 console.log(this),我可以看到格式正确且包含数据的所有内容(props.betAmounts)。但是,在同一个 componentDidMount() 中,当我 console.log(this.props.betAmounts) 我得到一个空对象...

这是一个带有显式问题的 codeSandBox(在控制台中可见)。

https://codesandbox.io/s/726jjqozzq

编辑 726jjqozzq

感谢您的帮助 !

标签: reactjsreact-props

解决方案


由于您是setState从您的内部调用,componentDidMount您将看到中间状态,因此在您的第一次渲染时,您betAmounts{}来自您的App状态,因此您将看到空对象。

componentDidMount有关于此的文档

Calling setState() in this method will trigger an extra rendering, but it will happen before the browser updates the screen. This guarantees that even though the render() will be called twice in this case, the user won’t see the intermediate state.

这意味着由于componentDidMount只调用一次,它将显示您的空对象,在第二次传递(来自额外触发的渲染)时,它将是您期望的对象。


推荐阅读