[英]Debugger inside React Context API Consumer block - this is undefined
我正在尝试使用浏览器开发工具中的render
方法中的Context API Consumer来调试组件。 如果我在Consumer
块中放置断点,我不能动态地在控制台上打印道具等,因为this
是undefined
。 通常运行它工作正常,但在调试时只有this
值是undefined
。 以下是组件的示例呈现方法。
componentMethod = () => {
console.log(this.props.name); //Placing breakpoint here, value is this is defined
}
render() {
return (
<div className={styles.container}>
<div>
<h4>{this.props.name}</h4>
</div>
<div className={styles.block}>
<MyComponent.Consumer>
{
({ firstParam, secondParam }) =>
<AotherComponent
firstParam={firstParam}
secondParam={secondParam}
thirdParam={this.props.name}
/>
}
</MyComponent.Consumer>
</div>
</div>
)
}
我可以在这里使用胖箭头,但是我可以在componentMethod
使用断点来获得这个值。 有没有办法将它bind
this
Consumer
块?
试试这个,但是,你的问题没有提供你想要解决的问题的足够背景。 如果您共享Provider
实现以及使用它的位置会更好。
render() {
const { name } = this.props;
return (
<div className={styles.container}>
<div>
<h4>{name}</h4>
</div>
<div className={styles.block}>
<MyComponent.Consumer>
{
({ firstParam, secondParam }) =>
<AotherComponent
firstParam={firstParam}
secondParam={secondParam}
thirdParam={name}
/>
}
</MyComponent.Consumer>
</div>
</div>
)
}
看起来您有兴趣了解您的消费者在执行期间传递给您的组件的内容。 有两种方法可以实现它。
让我们分析消费者的工作方式(使用您的样本)。 这可能有助于您找到正确的调试位置。
在render()
方法中,您有一个<MyComponent.Consumer>
调用。 新的Context Consumer API构建在render-prop模式上 。
关于render-prop模式需要记住的重要一点是:它是一个function
调用。 此函数应返回在渲染树时可以考虑的内容。
由于它是一个函数调用,您可以将console.log语句放在元素之前。 您必须添加一个显式的return
语句。
至于为什么它在你的方法中是undefined
的。 我假设componentMethod
不是生命周期方法,因此有可能是this
或this.props
是基于你如何调用该方法不明确的。 我没有在渲染方法中的任何地方看到它被调用。
使用react dev工具浏览器扩展。 您可以按名称查找所有组件。 点击它们你可以看到道具和状态,甚至是上下文(据我记得)。 你甚至可以改变的值,看看反应的反应吧!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.