简体   繁体   English

如何找出错误来自哪里?

[英]How to find out where the error is coming from in ReactJS?

I am getting this error because I am accidentally calling some method in my render method. 我收到此错误,因为我不小心在我的render方法中调用了某个方法。 As my application code is really big I'm unable to find out where is this coming from. 由于我的应用程序代码很大,因此我无法确定这是从哪里来的。 在此处输入图片说明

When I click on the index.js link in the console it is taking me to the following code. 当我单击控制台中的index.js链接时,它将带我到以下代码。 在此处输入图片说明

This is what I found after doing some debugging(call stack), But it's not the exact full component code, as there are too many lines of code in the component I'm just posting part of it here. 这是我在进行一些调试(调用堆栈)后发现的,但这并不是确切的完整组件代码,因为组件中的代码行太多,我只是在此处发布了一部分。 Is there anything wrong with this code: 这段代码有什么问题吗:

class Sample extends React.Component {
  constructor(props) {
    super(props);

    this.handleSelect = this.handleSelect.bind(this);

    this.state = {
      activeKey: '',
    };
  }
  handleSelect(activeKey) {
    this.setState({ activeKey });
  }

  render() {
    if (this.state.activeKey === '') {
      activeKey = this.getDefaultKey();
      this.handleSelect(activeKey);
    }
    return (
      <PanelGroup
        accordion
        activeKey={this.state.activeKey}
        onSelect={this.handleSelect}
      >
        {optionList}
      </PanelGroup>
    );
  }
}

You're calling this.handleSelect in the render function, which calls setState. 您正在渲染函数中调用this.handleSelect,该函数调用setState。 As the error says, you can't do this. 如错误所示,您无法执行此操作。 Can't say for sure without seeing the whole component and knowing what it's supposed to do, but my best guess at something that would at least not error: 在没有看到整个组件并且不知道应该做什么的情况下不能肯定地说,但是我最好的猜测是至少不会出错:

class SampleOptions extends React.Component {
  constructor(props, context) {
     super(props, context);

    this.handleSelect = this.handleSelect.bind(this);

    this.state = {
      activeKey: this.getDefaultKey(),
    };
  }
  handleSelect(activeKey) {
    this.setState({ activeKey });
  }

  render() {
    return (
      <PanelGroup
        accordion
        activeKey={this.state.activeKey}
        onSelect={this.handleSelect}
      >
        {optionList}
      </PanelGroup>
    );
  }
}

I would first use the react dev tools chrome extension first, you could also install the redux dev tools if you are using redux, both of these can find errors in state or props. 我首先要先使用react dev tools chrome扩展,如果您使用的是redux,也可以安装redux dev工具,这两个工具都可以发现state或props中的错误。

Most likely, though, there is an error in one of your components, and you should update your question with either snippets or a link to the codebase. 但是,最有可能的是,您的组件之一存在错误,您应该使用摘要或指向代码库的链接来更新您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM