javascript - 在调试 React 时找出谁在渲染组件
问题描述
假设我MyComponent
在我的应用程序的几个不同的地方进行了渲染。有人传递了错误的道具,导致组件代码出错。我暂停了错误,但我不知道的是:什么组件呈现了我?哪个组件呈现了该组件?有没有办法查看导致此渲染的组件实例的“堆栈跟踪”?
解决方案
是的,看看这里:https ://reactjs.org/blog/2017/07/26/error-handling-in-react-16.html#component-stack-traces
基本上你可以使用componentDidCatch
.
使用 React 15 或更低版本时
class MyComponent extends React.Component {
fallbackProps = {color: "red"};
render() {
const propsAreCorrect = checkProps(this.props);
if(!propsAreCorrect) alert("aah, something bad happend!");
const props = propsAreCorrect ? this.props : this.fallbackProps;
return <div color={props.color}></div>;
}
}
推荐阅读
- javascript - JS/AJAX 加载资源失败,服务器响应状态为 404(未找到)
- python - 如果在删除后立即调用,则获取请求返回 304 未修改
- node.js - Slack User Presence Subscription with Botkit startRtm
- javascript - 从 Google Drive 导出 docx 并转换为 base64
- php - 仅请求压缩数据
- c++ - C ++如何禁用具有不同符号变量比较的特定行的编译器警告?
- scala - scala中的特征参数
- node.js - 在 gulp 任务中使用路径模块时路径不正确
- angular - 如何测试第三方组件的输出是否在angular5中的事件上调用正确的函数
- javascript - 如何将 span id 的值分隔到另一个文件?