这是我的功能:
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>
);
}
但是如果我从构造函数中删除绑定(bind)(其实并不重要)并将按钮行更改为:
<button key={index} onClick={this.remove.bind(this, item)}>{item.search}: {item.text}</button>
所以我的问题是,有没有办法将它绑定(bind)在构造函数中,以便它可以接受参数?
最佳答案
this.remove(item)
和 this.remove.bind(this, item)
之间的区别在于,第一个调用函数,而第二个创建一个新函数。
So my question is, is there a way to bind it in the constructor so that it can take on the parameter?
您可以使用this.remove.bind(this, item)
和执行构造函数的绑定(bind),尽管这是不必要的。
如果您想将 item
传递给事件处理程序,那么您必须在 .map
中创建一个可以访问item
,使用您当前的设置。这可以通过 .bind 或通过闭包来完成。无论哪种情况,都不需要在构造函数中进行绑定(bind)。
如果以不同的方式提供item
,您只能避免创建新函数,例如用另一个以 item
作为 prop 的组件包装按钮(因此将函数创建进一步向下推):
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>
);
}
}
关于javascript - 如何在Reactjs中有参数的构造函数中绑定(bind)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41453744/