Using a Set data structure in React's state

前端 未结 2 1673
无人共我
无人共我 2021-02-03 19:45

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

相关标签:
2条回答
  • 2021-02-03 20:07

    state is just a common object, you can hold what ever you want in it. You can overwrite the shouldComponentUpdate lifecycle method to implement it yourself. You can use you own logic to figure out if the component needs to update or not. You don't even need to nest your set, you can just set it directly as the state:

    this.state = new Set();
    
    0 讨论(0)
  • 2021-02-03 20:11

    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);

    And this is how you use it in your class:

    export default class Checklist extends React.Component {
      constructor(props) {
        super(props);
    
        this.state = {
          checkedItems: new Set()
        }
    
        this.addItem = this.addItem.bind(this);
        this.removeItem = this.removeItem.bind(this);
      }
    
      addItem(item) {
        this.setState(({ checkedItems }) => ({
          checkedItems: new Set(checkedItems).add(item)
        }));
      }
    
      removeItem(item) {
        this.setState(({ checkedItems }) => {
          const newChecked = new Set(checkedItems);
          newChecked.delete(item);
    
          return {
           checkedItems: newChecked
          };
        });
      }
    
      getItemCheckedStatus(item) {
        return this.state.checkedItems.has(item);
      }
    
      // More code...
    }
    
    0 讨论(0)
提交回复
热议问题