常见的切换功能不适用于setState()

时间:2019-11-06 07:42:55

标签: reactjs typescript

我有一个代表此接口的状态:

StateInterface {
  variableOne: string;
  variableTwo: boolean;
  variableThree: boolean; 
  // ...
}

和切换功能:

toggleFunction = (value: keyof StateInterface): void => {
  this.setState((state) => ({
    [value]: !state[value]
  }));
};

在我的状态下,并非所有变量都是布尔值

但是TSLint告诉我该函数缺少某些属性。 我的状态只能使用一个切换功能吗?

4 个答案:

答案 0 :(得分:1)

那么,如何使您的函数只接受界面中布尔值的键呢?

interface IStateInterface {
  variableOne: string;
  variableTwo: boolean;
  variableThree: boolean;
  // ...
}

// here you make type filtered type
type FilterType<Base, Condition> = {
  [Key in keyof Base]:
  Base[Key] extends Condition ? Key : never
};

// so this is type where all type that don't go throught condition are "never"
type filteredState = FilterType<IStateInterface, boolean>;  

and here just pick the keys
type allowedKeys = filteredState [keyof filteredState];

因此在您的职能中,您拥有

toggleFunction = (value: allowedKeys ): void => {
  this.setState((state) => ({
    [value]: !state[value]
  }));
};

playground

答案 1 :(得分:0)

能否请您更详细地说明查询,以了解切换功能的作用。

从上方的切换功能中,我可以看到您正在更改布尔状态变量的状态。

variableOne (字符串)怎么办?

对于您的情况,您必须根据该值设置有条件的状态。

  

If-else可能会检查值是否为布尔值。

toggleFunction = (value: keyof StateInterface): void => {
   if (typeof variable === "boolean") 
{
  this.setState((prevState) => ({
    [value]: !prevState[value]
  }));
} else {
   this.setState((prevState) => ({
    [value]: 'Some value'
  }));
}

};

答案 2 :(得分:0)

对于setState方法,我们有2个使用选项:

在您的情况下,您使用了函数,因此将仅对属性进行突变,而不对所有状态的属性进行突变。

您可以尝试使用以下代码:

toggleFunction = (value: keyof StateInterface): void => {
  this.setState((state) => {
    value.forEach(property => {
    if( typeof(state[property]) != 'string'){ 
    state[property]= !state[property]
    }
  });
  return state;
};

答案 3 :(得分:0)

我不知道为什么,但是它有效:

...state

没有 // FirebaseUI for Cloud Firestore implementation 'com.firebaseui:firebase-ui-firestore:6.0.2' 时,我会收到有关缺少字段的错误

相关问题