Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Is it possible to use ES6's Set data structure in React?

For example, if I have a checklist composed of distinct items, and I'd like to maintain each item's checked state. I'd like to write something like this:

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

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

  addItem(item) {
    //...?
  }

  removeItem(item) {
    //...?
  }

  getItemCheckedStatus(item) {
    return this.state.checkedItems.has(item);
  }

  // More code...
}

I understand there may be a problem with the fact that a Set is mutable by nature, and React performs a shallow comparison when updating the component, so it expects immutable objects to be passed and held in the state. However, is there a way to hold and maintain a Set object in the state?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
210 views
Welcome To Ask or Share your Answers For Others

1 Answer

Since react will identify state changes only if the state property was replaced, and not mutated (shallow compare), you'll have to create a new Set from the old one, and apply the changes to it.

This is possible since new Set(oldSet) !== oldSet.

const oldSet = new Set([1, 2]);
const newSet = new Set(oldSet);

console.log(oldSet === newSet);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...