我正在使用设置数据结构来切换复选框。目前,检查处于工作状态,但取消检查不起作用。在检查时,我将发送所选项目的键/ ID,而在取消选中时,我尝试删除该键,但是它将整个checked
状态转换为布尔值。相反,它应该给我值为{'key1', 'key2'}
的已检查状态值,不包括“ key3”,因为key3的项未选中。这套immutable.js曾经可以使用,但不适用于本机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>
)
}
}
只有清除/取消选中部分无效,因为它将数据结构更改为布尔值。
最佳答案
要使用Sets真正实现有状态,您必须完全克隆它们,然后可以对其进行突变并调用setState:
toggle(key) {
this.setState(({ checked: previous }) => {
const checked = new Set(previous);
if(!checked.delete(key)) checked.add(key);
return { checked };
});
}
您的代码无效,因为
delete
返回的是布尔值,而不是Set。关于javascript - 使用Set时,取消选中项不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51617660/