首页 > 解决方案 > 在调试 React 时找出谁在渲染组件

问题描述

假设我MyComponent在我的应用程序的几个不同的地方进行了渲染。有人传递了错误的道具,导致组件代码出错。我暂停了错误,但我不知道的是:什么组件呈现了我?哪个组件呈现了该组件?有没有办法查看导致此渲染的组件实例的“堆栈跟踪”?

标签: javascriptreactjsdebugging

解决方案


是的,看看这里: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>;
  }
}

推荐阅读