gpt4 book ai didi

javascript - 使用 Set 时取消选中项目不起作用

转载 作者:行者123 更新时间:2023-12-03 01:24:19 26 4
gpt4 key购买 nike

我正在使用设置数据结构来切换复选框。目前,检查有效,但取消选中无效。检查时,我发送所选项目的键/id,取消选中时,我尝试删除该键,但它将整个 checked 状态转换为 bool 值。相反,它应该给我检查状态的值,如 {'key1', 'key2'} 不包括 'key3',因为 key3 的项目未被选中。 immutable.js 集合曾经可以工作,但不能在 native JavaScript 中工作。

这是我所做的

class DeviceHome extends React.Component<propsCheck> {
constructor() {
super();
this.state = { checked: new Set(), group: '' };
}
componentWillReceiveProps(nextProps) {
try {
if (!nextProps.activeGroup.equals(this.props.activeGroup)) {
this.setState({ checked: new Set() });
}
} catch (e) {}
}

toggle(key) {
const { checked } = this.state;
this.setState({
checked: checked.has(key) ? checked.delete(key) : checked.add(key),
});
}

toggleAll() {
const { checked } = this.state;
this.setState({
checked: checked.size === 0 ? checked.values(this.props.devices) : checked.clear(),
});
}
render() {
const { checked } = this.state;
console.log('checked', checked, typeof checked);
const indeterminate = Boolean(checked.size) && checked.size < Object.keys(this.props.devices).length;
const devices = Object.entries(this.props.devices).map(([key, value]) => {
const { name, connection_timeout: connectionTimeout } = value;
return (
<Table.Row key={key} active={checked.has(key) || false}>
<Table.Cell>
<Checkbox checked={checked.has(key)} onChange={() => this.toggle(key)} />
</Table.Cell>
</Table.Row>
)
});
return (
<Wrapper>
<Table unstackable structured>
<Table.Row>
<Table.HeaderCell>
<Checkbox
onChange={() => this.toggleAll()}
indeterminate={indeterminate}
checked={
Boolean(checked.size) &&
checked.size === Object.keys(this.props.devices).length
}
/>
</Table.HeaderCell>
</Table.Row>
<Table.Body>{devices}</Table.Body>
</Table>
</Wrapper>
)
}
}

仅清除/取消选中部分不起作用,因为它将数据结构更改为 bool 值。

最佳答案

要真正实现 Sets 的有状态性,您必须完全克隆它们,然后您可以改变它并调用 setState:

 toggle(key) {
this.setState(({ checked: previous }) => {
const checked = new Set(previous);
if(!checked.delete(key)) checked.add(key);
return { checked };
});
}

你的不起作用,因为delete返回一个 bool 值,而不是一个Set。

关于javascript - 使用 Set 时取消选中项目不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51617660/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com