代码之家  ›  专栏  ›  技术社区  ›  milan

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

  •  0
  • milan  · 技术社区  · 6 年前

    我使用Set data structure切换复选框。目前,该检查正在工作,但取消选中不工作。检查时,我发送所选项目的键/id,取消检查时,我试图删除该键,但它转换了整个 checked 状态为布尔值。相反,它应该给我checked state的值 {'key1', 'key2'} 不包括“key3”,因为key3的项未选中。不可变.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>
        )
      }
    }
    

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

    1 回复  |  直到 6 年前
        1
  •  1
  •   Jonas Wilms    6 年前

    要真正实现集合的有状态性,必须完全克隆它们,然后可以对其进行变异并调用setState:

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

    你的不起作用是因为 delete 返回布尔值,而不是集合。