[英]React / Material-UI onClick event trigger more than once when use in data.map() Loop
First, my English is not so good. 首先,我的英语不太好。
{data.sort(getSorting(order, orderBy)) .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage) .map(n => { ........ <Button onClick={this.handleLsClick}> Open Menu </Button> <Dialog onClose={this.handleLsClose} aria-labelledby="simple-dialog-title" open={open} > <div> <List> {[1,2,3,4,5].map(e => ( <ListItem button key={e}> <ListItemText primary={e} /> </ListItem> ))} </List> </div> </Dialog> .........
Basically this codes works fine, But if I put them into the Loop (Like fetch data from Database), When I click the Button to show data, onClick events fired more than once, Actually fired until == "data.length" ! 基本上,这些代码可以正常工作,但是如果我将它们放入循环中(就像从数据库中获取数据一样),则当我单击按钮以显示数据时,onClick事件会触发多次,实际上会触发直到==“ data.length”!
You can see Full sample on CodeSandbox for better Information. 您可以在CodeSandbox上查看完整示例,以获取更多信息。
At code sandbox Click the "OPEN MENU", and you will see that What's happened. 在代码沙箱中,单击“打开菜单”,您将看到发生了什么。 For more clarity,open demo.js and find "data" array at Line 199, Set just 1 entry and you will see that onClick event run just once, But if you Add more entry the onClick event Fired more and more...
为了更加清晰,请打开demo.js并在第199行找到“数据”数组,仅设置1个条目,您将看到onClick事件仅运行一次,但是如果您添加更多条目,则onClick事件会越来越多地触发...
Any ideas Guys? 有什么想法吗? Thanks Btw.
谢谢顺便说一句。
I've made a workaround to solve this problem (Because I don't know if this is a bug or not, I called that workaround). 我已经解决了这个问题(因为我不知道这是否是一个错误,所以我称之为解决方法)。
First, move Dialog out of the loop . 首先, 将Dialog移出循环 。 I did it with custom Component.
我用自定义组件做到了。
class MyDialog extends React.Component {
constructor(props) {
super(props)
}
render() {
return (
<div>
<Dialog
onClose={this.props.onClose}
aria-labelledby="simple-dialog-title"
open={this.props.openState}
>
<div>
<List>
{this.props.myList.map(e => (
<ListItem button key={e.id}>
<ListItemText primary={e.name} />
</ListItem>
))}
</List>
</div>
</Dialog>
</div>
);
};
}
Then call it like that in Loop: 然后在Loop中这样调用它:
<Button onClick={this.handleLsClick} data-ids={n.id}>Open Menu</Button>
I can post complete code, But In our Language there is a proverb that says: "Bring some pressure to your brain". 我可以发布完整的代码,但是在我们的语言中有一句谚语说:“给大脑施加压力”。 However, the code is complete right now.
但是,代码现在已经完成。
I used the dataset to be able to identify and separate information from each other. 我使用数据集来识别和分离信息。
For me, this code is not all I want, more work to do for separating data. 对我来说,这段代码并不是我想要的,而是要做更多的工作来分离数据。 But I think it answers this question.
但是我认为它回答了这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.