React with TypeScript:构造函数中的状态启动

React with TypeScript: State Initiations in constructor

我在 TypeScript React App 中有一个长格式,我们需要根据状态值 hide/show 或 enable/disable。

export interface IState {
  Status: string;
  DisableBasicForm: boolean;
  DisableFeedbackCtrl: boolean;
  DisableTypeofReqCtrl: boolean;
  DisablePurposeCtrl: boolean;
  DisableDutyStation: boolean;
  DisableContractManager: boolean;
  DisableSection: boolean;
  DisableStartDate: boolean;
  DisableEndDate: boolean;
  DisableEstimateDate: boolean;
  DisableTotalBudget: boolean;
  DisableDeliveryDate: boolean;
  DisableWBS: boolean;
  DisableGrant: boolean;
  DisableGrantExpiry: boolean;
  DisableCaseSubmitter: boolean;
  DisablePreparedBy: boolean;
  DisablePreparedDate: boolean;
  ShowSupplyManagerPanel: boolean;
  ShowBudgetOwnerPanel: boolean;
  DisableSupplyManagerPanel: boolean;
  DisableBudgetOwnerPanel: boolean;
}

而在 class 中,我需要在构造函数中启动状态,最好的方法是什么,我不需要启动 IState 中存在的非常多变的状态?

public constructor(props: IGoodsProps) {
    super(props);
//What should be written here, minimal code required.
}

如果声明实现 IState,则需要启动每个 属性 IState(根据您的逻辑),因为 IState 中的属性未标记为可选。

伪代码示例:

public constructor(props: IGoodsProps) {
    const {status} = this.props
     super(props);
     this.state ={
       Status: status,
       DisableBasicForm: status.Status === 'yourValue',
       ... // initialize here
    } 
}

如果你有一些作为 prop 传递的状态的默认值,你可以使用对象解构器:

public constructor(props: IGoodsProps) {
    const {status} = this.props
     super(props);
     this.state ={
       ...status,
       DisableBasicForm: status.Status === 'yourValue', // just overwrite this property with your logic
    } 
}

你也可以在构造函数之外初始化你的状态:

class Component extends React.Component<Props, State> {
  state: State = {
    Status: 'value',
    ... // initialize here
  }

  constructor(props: Props) {
   ...
  }

如果您有一些用于设置状态的共享逻辑,并且不想重复自己,您可以使用 React.useState 进行评估,但您的组件需要是一个函数。

如果您同意某些属性的默认值为 undefined,您可以使用 ?IState 中将它们标记为可选。例如(由于不知道您的要求,我随机选择了一些属性):

export interface IState {
  Status: string; // this one is required
  DisableBasicForm?: boolean; // this one is optional
  DisableFeedbackCtrl?: boolean;
  // ...
}

然后在构造函数中初始化状态时可以省略可选属性。

哪些属性可选? 如果您希望任何布尔值默认为 false,在许多情况下 undefined 会起作用,因为 undefined is "falsey" 在 JavaScript。 (如果这没有意义,可以更详细地说明)