[英]How to bind function in constructor that has a parameter in 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>
所以我的问题是,有没有一种方法可以将其绑定到构造函数中,以便可以采用参数?
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>
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.