作为新手反应开发者,我刚刚意识到,我一直在无意中改变状态和道具直接。
有很多例子:

const {variable} = this.props;
variable[index] = value;
// do something local with var - not realizing that variable is changed

在我的代码库中有数百个这样的实例。
是否有tslint规则或方法,我可以找到每个实例,我已经变异道具或状态,应该是只读的。
我知道那里有一条关于
TS2540: Cannot assign to ‘url’ because it is a constant or a read-only property.
但我不知道怎么打开它。根据我的理解,在反应式脚本中,道具和状态被封装在RealDime>中,当我试图改变道具或状态时,应该触发这个错误。

最佳答案

您可以在创建接口时声明它们为readonly,并使用ReadonlyArray数组,用于您的道具和状态,例如:

interface ButtonProps {
  readonly onChange: (event: ChangeEvent) => void;
  readonly classes: ReadonlyArray<string>;
}

class Button extends React.Component<ButtonProps> { ... }

这样,只要所有成员都readonly,就应该到处进行检查,而出错的是typescript编译器,而不是tslint。
您可以做的一件事是使用tslint-immutable中的规则来确保在接口和数组上不会漏掉任何readonly

关于reactjs - 使用tslint强制不变性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54408550/

10-11 23:44