如何调试 React 应用中的 JavaScript 类?

huangapple go评论76阅读模式
英文:

How do I debug a Javascript class that is part of a React application?

问题

当我开发一个React组件时,我使用console.log()语句进行调试。当组件被渲染时,console.log()语句会被打印到控制台,这是我目前用于调试的全部内容。

但是,我如何调试JavaScript类呢?我想在JavaScript类中也使用我的console.log()语句。但是该类本身不会被渲染到DOM中,所以位于该类中的console.log()语句也不会被打印到控制台。

一个简单的JavaScript类。

class MyClass {
  constructor(name) {
    this.name = name;
  }

  sayHello() {
    console.log(`Hello, ${this.name}!`);
  }
}
英文:

When I develop a React Component, I use the console.log() statement for debugging. When the component is rendered, the console.log() statement is printed into the console and that is all that I presently use for my debugging.

But how do I debug a javascript class? I would like to use my console.log() statements also in a Javascript class. But how can I do that? The problem is that the class itself does not get rendered into the DOM, so the console.log() statements [placed in the class] are also not printed into the console.

A simple Javascript class.

class MyClass {
  constructor(name) {
    this.name = name;
  }

  sayHello() {
    console.log(`Hello, ${this.name}!`);
  }
}

答案1

得分: 1

只有在从实例调用函数sayHello时,才会执行console.log(),然后您可以在控制台中看到它。现在您没有在任何地方调用sayHello

class MyClass {
  constructor(name) {
    this.name = name;
  }

  sayHello() {
    console.log(`Hello, ${this.name}!`);
  }
}

const obj = new MyClass('Jimmy Dean');
obj.sayHello()
英文:

Only when you call the function sayHello from an instance will the console.log() execute and you can see it inside the console. Right now you are not calling sayHello anywhere.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

class MyClass {
  constructor(name) {
    this.name = name;
  }

  sayHello() {
    console.log(`Hello, ${this.name}!`);
  }
}

const obj = new MyClass(&#39;Jimmy Dean&#39;);
obj.sayHello()

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年6月1日 00:35:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76375645.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定