在create-react-app中调试es6

问题描述 投票:2回答:2

我正在尝试调试create-react-app,当我在箭头函数上设置断点时,我在this关键字中有无效值,并且停止断点的完全奇怪的行为(devtools不允许在有效的js表达式中放置断点,它看起来比如禁用断点。我检查了FF和Chrome浏览器。但是,当我将箭头功能(()=>{})更改为function(){}声明时,调试行为是正确的。有谁知道问题是什么以及启动项目的反应是什么你建议正确调试箭头功能的地方吗?

我在App.js中的代码看起来像here。尝试在行内放置一个断点:

this.setState({value: this.state.value + 1})

this应该是App但事实并非如此。虽然应用程序的行为是正确的,但在这个特定的断点处是undefined。我怀疑有些东西被源图破坏了......什么是反应项目,有良好的设置,webpack正确处理源图?

reactjs ecmascript-6 create-react-app
2个回答
3
投票

如果不使用像let that = this这样的东西,你可以用几种不同的方式在JSX属性中使用函数进行回调。

如果你想直接使用它作为匿名函数,你可以这样使用:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: 0,
    };
  }

  render() {
    return (
        <button onClick={(function () {
          this.setState(prevState => ({ value: prevState.value + 1 }));
        }).bind(this)}>
        Click me
        </button>
    );
  }
}

你直接将函数绑定到this。我还没有看到任何这方面的例子。一般人们使用这样的东西:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: 0,
    };
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState(prevState => ({ value: prevState.value + 1 }));
  }

  render() {
    return (
        <button onClick={this.handleClick}>
        Click me
        </button>
    );
  }
}

这里我们使用我们的回调函数作为引用并将其绑定到构造函数中。

另一种选择是使用箭头功能。对于这种情况,您不需要绑定您的函数。此外,我们在这里使用类字段,因此根本不需要使用构造函数。

class App extends React.Component {
  state = { value: 0 };
  handleClick = () => {
    this.setState(prevState => ({ value: prevState.value + 1 }));
  }

  render() {
    return (
        <button onClick={this.handleClick}>
        Click me
        </button>
    );
  }
}

在JSX道具this的范围更改的回调中,它不再引用该类。所以你要么将它绑定到this,要么使用不改变this范围的箭头函数。


2
投票

在这些情况下,有时调试工具很难为lambda函数正确放置断点。也许您可以通过将debugger临时添加到源代码中来实现相同的效果,如下所示,强制断点点击:

import React, {Component} from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {

    constructor(props) {
        super(props);
        this.state = {
            value: 0,
        };
    }

    render() {

        return (
            <div className="App">
                <header className="App-header" onClick={() => {

                    debugger; // ADD THIS: It will act as a breakpoint and force the developer-tools to break so you can step through the code

                    this.setState({value: this.state.value + 1})
                }}>
                    <img src={logo} className="App-logo" alt="logo"/>
                    <h1 className="App-title">Welcome to React, the state is {this.state.value}</h1>
                </header>
                <p className="App-intro">
                To get started, edit <code>src/App.js</code> and save to reload.
                </p>
        </div>);
    }
}

export default App;
© www.soinside.com 2019 - 2024. All rights reserved.