简体   繁体   中英

React JSX loop on Set() object

I want to use Set object to store unique values. but by default we can't use Set.map() to make a loop on Set values in React and JSX.

But with this trick I can store Set into states and make a loop on that :

 <ul> { Array.from(this.state.mySet).map((item, index) => ( <li key={index}>{item}</li> )) } </ul>

So, Is the above trick correct and best practice to handle this issue ?

In terms of performance and concepts ...

Thanks

This is fine but react identifies state changes only if the state property was replaced, and not mutated/shallow compare. You'll have to use the old Set to create a new Set and then apply changes to it. That way you won't have to force update the state.

export default class Test extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      mySet: new Set()
    }

    this.add = this.add.bind(this);
  }

  add(item) {
    this.setState(({ mySet }) => ({
      mySet: new Set(mySet).add(item)
    }));
  }


  /*
  .
  .
  . Other code
  . 
  . */
}

Hope this helps !

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