简体   繁体   中英

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" !

You can see Full sample on CodeSandbox for better Information.

编辑材料演示

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...

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 . 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:

<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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM