【问题标题】:React, Noob issue反应,菜鸟问题
【发布时间】:2018-01-12 18:00:07
【问题描述】:

经历了一些简单的 React 初学者挑战并陷入困境。显然我得到了足够的信息来解决这个问题,但不能。尝试了许多不同的代码组合,但仍然无法正常工作。

Challenge:Counter 组件跟踪状态中的计数值。有两个按钮调用方法 increment() 和 decrement()。编写这些方法,以便在单击相应按钮时计数器值递增或递减 1。另外,创建一个 reset() 方法,以便在单击重置按钮时将计数设置为 0。

注意:确保不要修改按钮的类名。

我的代码:

class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    }
  };
  // change code below this line

  increment() {
    this.setState({
      this.state.count: this.state.count + 1
    });
  };

  decrement() {
    this.setState({
      this.state.count: this.state.count - 1
    });
  };

  reset() {
    this.setState({
      this.state.count: 0
    });
  };

  // change code above this line
  render() {
    return (

   <div>
   <button className='inc' onClick={this.increment}>Increment!</button>
    <button className='dec' onClick={this.decrement}>Decrement!</button>
    <button className='reset' onClick={this.reset}>Reset</button>
    <h1>Current Count: {this.state.count}</h1>
  </div>
    );
  }
};

我做错了什么?

【问题讨论】:

标签: reactjs


【解决方案1】:

我发现有两件事可能是错误的:

  1. 不在构造函数中绑定事件处理程序
  2. setState() 中的对象语法无效

在您的构造函数中,确保在事件处理程序上使用bind(),以便它们可以访问正确的this 上下文:

  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
    this.increment = this.increment.bind(this);
    this.decrement = this.decrement.bind(this);
    this.reset = this.reset.bind(this);
  };

当您设置状态时,对象语法看起来是错误的。不能设置{foo.foo: bar}:

  increment() {
    this.setState({
      count: this.state.count + 1
    });
  };

【讨论】:

【解决方案2】:

您似乎没有将this 绑定到您的事件处理函数。

将此添加到您的构造函数中,它应该可以工作。

this.increment = this.increment.bind(this);
this.decrement = this.decrement.bind(this);
this.reset = this.reset.bind(this);

来自React docs:

在 JSX 回调中你必须小心 this 的含义。在 JavaScript 中,默认情况下不绑定类方法。如果忘记绑定 this.handleClick 并传递给 onClick,那么在实际调用函数时 this 将是未定义的。

这不是 React 特有的行为;它是功能的一部分 在 JavaScript 中工作。一般来说,如果你引用一个没有()的方法 在它之后,例如 onClick={this.handleClick},你应该绑定它 方法。

编辑:查看您的 codepen 后,您需要将此行添加到文件底部:

ReactDOM.render(<Counter />, document.getElementById('container'));

阅读this。

【讨论】:

【解决方案3】:

您需要绑定您的方法调用,以便它们正确引用组件实例:

<button className='inc' onClick={this.increment.bind(this)}>Increment!</button>
<button className='dec' onClick={this.decrement.bind(this)}>Decrement!</button>
<button className='reset' onClick={this.reset.bind(this)}>Reset</button>

还有其他策略,比如在构造函数中绑定,

this.increment = this.increment.bind(this); // etc

更多explained in this blog post.

【讨论】:

  • 谢谢,但由于代码告诉我我只应该触摸 cmets 之间的内容,我认为我不应该触摸那些。有没有办法在评论区做到这一点?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多