reactjs - 使用 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<> 中,每当我尝试改变道具或状态时,它都会触发此错误。
解决方案
您可以readonly
在创建接口并ReadonlyArray
用于数组、道具和状态时声明它们,例如:
interface ButtonProps {
readonly onChange: (event: ChangeEvent) => void;
readonly classes: ReadonlyArray<string>;
}
class Button extends React.Component<ButtonProps> { ... }
这样,只要所有成员都是readonly
,您就应该在任何地方进行检查,并且会出错的是打字稿编译器,而不是 tslint。
您可以做的一件事是使用来自tslint-immutable的规则,以确保您不会错过任何readonly
接口和数组
推荐阅读
- javascript - 基本 JS 文件加载但不渲染或执行 Laravel 8 Bootstrap 5
- react-native - 如何从选项卡导航器打开抽屉导航器
- javascript - 通过 DOM 操作更改 SVG 笔触颜色
- python - 单击单选按钮 Selenium/Python
- java - Java 8+ 流、泛型和 lambda 表达式
- android - 改造:如何从 okhttp 拦截器再次重试请求?
- java - 如何编写反转二维数组的方法
- javascript - 有人可以帮我解决这个 React 教程语法错误吗?
- sql - SQL INSERT 查询无法执行
- assembly - 如何使用 qemu 引导我的引导扇区文件?