我正在学习React。我在我的状态中有一个数组,我通过映射来将数组中的每个值呈现在它自己的按钮上。当用户点击其中一个按钮时,我想调用一个函数来显示该按钮的一些特定信息(该按钮代表一个特定的客户订单)。我试着在onClick事件中设置状态,但得到了一个 "超过了最大更新深度 "的错误。如果有办法在onClick事件中设置状态,那就可以解决我的问题了,因为我可以将被点击的特定按钮的项目值设置为状态,然后再使用它。我的另一个想法是将项目发送到showInfo函数...然而,我甚至不知道这是否可行。我怎样才能从这个按钮列表中调用同样的函数,并使结果对按钮来说是唯一的?
showInfo = (e) => {
}
componentDidMount() {
this.showAllOrders();
}
render() {
return (
<div>
<h1>Hello from past orders!!!</h1>
<ul id="orderList">
{this.state.orderDates.map((item =>
<li><button onClick={this.showInfo} key={item}>{item}</button></li>
))}
</ul>
</div>
)
}
}
使用 内联箭头函数 作为你的onClick的回调,然后传递你想要的数据。
...
showInfo = (item) => {
console.log(item);
}
...
render() {
return (
<div>
<h1>Hello from past orders!!!</h1>
<ul id="orderList">
{this.state.orderDates.map((item =>
<li><button onClick={() => this.showInfo(item)} key={item}>{item}</button></li>
))}
</ul>
</div>
)
另外,千万不要在你的渲染方法中设置状态,这就是为什么你得到了 max depth error
在你之前的尝试中。
您可以提供以下功能 showInfo
通过params与按钮的信息。
因此,它将是 onClick={() => this.showInfo(item)}