【问题标题】:Updating array in react state, using concat使用 concat 更新处于反应状态的数组
【发布时间】:2019-12-22 10:25:22
【问题描述】:

我有一个复选框组件,基本上我想做的是制作选中的数组并将信息发送到 api。 但我无法在不删除最后插入的对象的情况下更新状态数组。 我正在使用 concat 并且仍然是相同的结果。 这是整个组件的代码:

import React, { Fragment, Component } from 'react';
import { Inputt, Checkbox } from './style';

interface Istate {
  checked: boolean;
  products?: any[];
}
interface Iprops {
  id: any;
  value: any;
  changeValue?: (checkBoxId: string, value: any) => void;
}
class CheckBoxComp extends Component<Iprops, Istate> {
  state = {
    checked: true,
    products: [] as any,
  };

  addOne = (id: any, checked: any) => {
    let { products } = this.state;
    const newObj = { id, checked };
    products = products.concat(newObj);
    this.setState({ products }, () => {
      console.log(products);
    });
  };

  isChecked = (id: any) => {
    const { checked, products } = this.state;
    const { changeValue } = this.props;
    this.setState({
      checked: !checked,
    });
    if (changeValue) {
      changeValue(id, checked);
    }
    this.addOne(id, checked);
  };

  render() {
    const { id, value } = this.props;
    const { checked, products } = this.state;
    return (
      <Fragment>
        <Checkbox>
          <span />{' '}
          <label className="checkbox-wrapper">
            <span className="display" />
            <Inputt
              type="checkbox"
              value={checked}
              onChange={() => {
                this.isChecked(id);
              }}
            />
            <span className="checkmark" />
          </label>
        </Checkbox>
      </Fragment>
    );
  }
}

export default CheckBoxComp;

【问题讨论】:

    标签: javascript reactjs typescript checkbox setstate


    【解决方案1】:

    您可以尝试这种利用扩展运算符制作数组副本的方法:

    addOne = (id: any, checked: any) => {
        this.setState((state: Istate): Partial<Istate> => ({
            products: [
                ...state.products,
                { id, checked },
            ],
        }), () => console.log(this.state.products));
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-22
      • 2020-03-29
      • 1970-01-01
      • 2019-11-08
      • 1970-01-01
      • 2021-08-10
      • 1970-01-01
      • 2016-01-19
      相关资源
      最近更新 更多