组件正在更改类型复选框的不受控制的输入以在React JS中进行控制

时间:2019-01-25 11:55:15

标签: reactjs typescript error-handling warnings

警告:组件正在更改要控制的复选框类型的不受控制的输入。输入元素不应从不受控制切换为受控制(反之亦然)。在组件的使用寿命中决定使用受控还是不受控制的输入元素。

我的代码:

sqlite3.connect(...., factory=ChronologyConnection)

      interface IState {
      isSelectedAll: boolean;
      selected: any;
      confirmDelete: boolean;
      confirmSignStatus: boolean;
      petitionId: any;
      items: any;
      verificationCode: any;
    }
...
    /**
     * Default state.
     */
    function getDefaultState(): IState {
      return {
        isSelectedAll: false,
        selected: {},
        confirmDelete: false,
        confirmSignStatus: false,
        petitionId: '',
        items: [],
        verificationCode: null,
      };
    }

  public handleSelect = (id: number) => {
    let selectedObj = Object.assign({}, this.state.selected);
    selectedObj[id] = !selectedObj[id];
    this.setState({ selected: selectedObj });
  }
...

  public state: IState = getDefaultState();


 public componentWillReceiveProps(nextProps: any): void {
    if (nextProps.ecourtListBranch.data) {
      this.initSelects(nextProps.ecourtListBranch.data);
    }
  }

      private initSelects = (data: any): void => {
        let selectedObj: any = {};
        data.map((item: IPetitionView) => {
          selectedObj[item.petitionId] = false;
          this.setState({ selected: selectedObj });
        });
      }

1 个答案:

答案 0 :(得分:1)

这意味着this.props.selecteds [petitionId]有时是不确定的。您可以做的一件事就是像这样为复选框提供默认值。

<Checkbox
  value={this.props.selecteds[petitionId] || false}
  onChange={() => handleSelect(petitionId)}
 />

警告说明:请勿使用defaultValue属性,因为它会使您的组件不受定义的控制。