如何在Reactjs中具有参数的构造函数中绑定函数

时间:2017-01-03 23:07:09

标签: javascript reactjs

所以这是我的功能:

remove(element)
{   
    this.setState({ search: this.state.search.filter( item => item !== element ) }); 
}  

我收到此错误:

Warning: setState(...): Cannot update during an existing state transition (such as within `render` or another component's constructor). 
Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to `componentWillMount`.

如果我这样设置:

constructor()
{
    this.remove = this.remove.bind(this);
}
render() 
{   
    return (
        <div>
            { this.state.search.map( (item, index) =>  
                (   
                    <button key={index} onClick={this.remove(item)}>{item.search}: {item.text}</button>
                ))  
            }   
            </div>
        </div>
    );
}

但是如果我从构造函数中删除绑定(好吧并不重要),并将按钮行更改为:

<button key={index} onClick={this.remove.bind(this, item)}>{item.search}: {item.text}</button>

所以我的问题是,有没有办法在构造函数中绑定它以便它可以采用参数?

1 个答案:

答案 0 :(得分:3)

this.remove(item)this.remove.bind(this, item)之间的区别在于第一个调用函数,而第二个创建一个新函数。

  

所以我的问题是,有没有办法在构造函数中绑定它以便它可以采用参数?

您可以使用this.remove.bind(this, item) 执行绑定构造函数,但这是不必要的。

如果您想将item传递给事件处理程序,那么您必须.map中创建一个可以访问item的新功能目前的设置。这可以通过.bind或通过闭包来完成。在任何一种情况下,构造函数中的绑定都不是必需的。

如果以不同的方式提供item,您只能避免创建新功能,例如用另一个以item作为道具的组件包裹按钮(因此进一步推动功能创建):

function Button({item, onClick}) {
  return <button onClick={() => onClick(item)}>{item.search}: {item.text}</button>;
}

class Component extends React.Component {
  constructor()
  {
      this.remove = this.remove.bind(this);
  }

  render() 
  {   
      return (
          <div>
              { this.state.search.map( (item, index) =>  
                  (   
                      <Button key={index} onClick={this.remove} item={item} />
                  ))  
              }   
              </div>
          </div>
      );
  }
}
相关问题