React onClick 不断触发

React onClick keeps triggering

当我触发 onClick 时,事件甚至会持续触发大约 1000 多次。我似乎无法弄清楚这是从哪里来的。我已将 onClick 更改为 onMouseover 以查看它是否继续触发,但事件仅触发一次。

我正在使用:react 0.13.3

有什么想法吗?

var React = require('react');
var AppActions = require('../../actions/app-actions.js');


var FileAmount = React.createClass({
 getInitialState: function() {
  return {
   amount : this.props.amount,
   config : this.props.config
  };
 },
 handleClick: function(e){
  var name = e.target.name;
  if(name === 'decrease'){
   if(this.state.amount > 1){
    this.setState({
     amount : (this.state.amount  - 1)
    });
    AppActions.updateAmount(this.props.index, (this.state.amount  - 1))
   }
  }else{
   this.setState({
     amount : (this.state.amount + 1)
   });
   AppActions.updateAmount(this.props.index, (this.state.amount + 1))
  }
 },
 handleChange: function(e){
  var amount = e.target.value;
  this.setState({
   amount : amount
  });
  AppActions.updateAmount(this.props.index, amount)
 },
 render: function() {

  var config = this.state.config
  
  return (
   <div className="file-amount">
    <span className="file-amount-text"> {config.filelist_quantity}: {this.state.amount} {config.filelist_pieces}</span>
    <div className="file-amount-fields">
     <i className="file-amount-decrease icon" name="decrease" onClick={this.handleClick} /> 
      <input className="file-amount-input" type="number" value={this.state.amount} onChange={this.handleChange} />
     <i className="file-amount-increase icon" name="increase" onClick={this.handleClick} /> 
    </div>
   </div>
  );
 }
});

module.exports = FileAmount;

也许添加一个e.preventDefault();到您的 handleClick 方法将停止此循环的启动。

我删除了为浏览器同步代理设置添加的 javascript。这不知何故搞砸了我的反应。

我在原 post 上留下了评论,但在第二次检查时,看起来很可能您从 Flux Store 传下来 props.amount。如果是这种情况,您正在创建一个无限循环。

handleClick 递增 state.amount,然后在调用 AppAction 后,Store 使用 props.amount 更新组件,然后 onChange 触发,因为它绑定到 state.amount 然后 onChange 更改 state.amount 并在调用 AppActions.updateAmount 时更改 props.amount

每次propsstate更新时,React都会调用render()方法。如果有任何方法 propsstate 得到更新 render() 执行,那么你可能会 运行 进入无限循环。