在React状态下使用Set数据结构 [英] Using a Set data structure in React's state
问题描述
是否可以在React中使用ES6的 Set
数据结构?
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...
}
我知道Set本质上是可变的,并且在更新组件时React会进行浅表比较,因此它可能会传递不可变的对象并保持其状态,这可能是一个问题.但是,有没有一种方法可以将Set对象保持和保持在该状态?
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?
推荐答案
由于只有在状态属性被替换且未突变(浅比较)的情况下,react才会识别状态更改,因此您必须从旧版本,然后对其进行更改.
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.
这是可能的,因为 new Set(oldSet)!== oldSet
.
const oldSet = new Set([1, 2]);
const newSet = new Set(oldSet);
console.log(oldSet === newSet);
如何在类组件中使用Set:
How you use a Set in a class component:
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...
}
如何通过 useState()
挂钩使用集合:
const Comp = () => {
[state, setState] = useState(() => new Set());
const addItem = item => {
setState(prev => new Set(prev).add(item));
}
const removeItem = item => {
setState(prev => {
const next = new Set(prev);
next.delete(item);
return next;
});
}
return /* JSX */;
}
这篇关于在React状态下使用Set数据结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!