首页 > 解决方案 > 使用 tslint 强制执行不变性

问题描述

作为一名新手 React 开发人员,我刚刚意识到我一直在不经意间直接改变了 state 和 props。

有很多例子:

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

我的代码库中有数百个这样的实例。

是否有一个 tslint 规则或一种方法可以找到我已经突变的 props 或 state 应该是只读的每个实例。

我知道有一个 tslint 排除沿线

TS2540: Cannot assign to ‘url’ because it is a constant or a read-only property.

但我不知道如何打开它。据我了解,在 React Typescript 中,道具和状态被包裹在 Readonly<> 中,每当我尝试改变道具或状态时,它都会触发此错误。

标签: reactjstypescripttslint

解决方案


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

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

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

这样,只要所有成员都是readonly,您就应该在任何地方进行检查,并且会出错的是打字稿编译器,而不是 tslint。

您可以做的一件事是使用来自tslint-immutable的规则,以确保您不会错过任何readonly接口和数组


推荐阅读