简体   繁体   English

在 Set() 对象上反应 JSX 循环

[英]React JSX loop on Set() object

I want to use Set object to store unique values.我想使用 Set 对象来存储唯一值。 but by default we can't use Set.map() to make a loop on Set values in React and JSX.但默认情况下,我们不能使用 Set.map() 在 React 和 JSX 中对 Set 值进行循环。

But with this trick I can store Set into states and make a loop on that :但是通过这个技巧,我可以将 Set 存储到状态中并对其进行循环:

 <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.这很好,但只有当 state 属性被替换时,react 才会识别状态更改,而不是变异/浅比较。 You'll have to use the old Set to create a new Set and then apply changes to it.您必须使用旧的 Set 来创建一个新的 Set,然后对其应用更改。 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 !希望这可以帮助 !

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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