由于只有当 state 属性被替换而不是突变(浅比较)时,react 才会识别状态更改,因此您必须从旧的 Set 中创建一个新的 Set,并将更改应用于它。
这是可能的,因为new Set(oldSet) !== oldSet
.
const oldSet = new Set([1, 2]);
const newSet = new Set(oldSet);
console.log(oldSet === newSet);
如何在类组件中使用 Set:
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 */;
}