常见错误

下面给出了常见的 lint 语法错误,以及解决方法。

1. 常见 Lint 错误

1.1. 忽略错误

如果实在解决不了,可以忽略这个错误。

可以用这个方法,vscode提示错误,但是eslint没有提示错误

// @ts-ignore

eslint 提示错误时,用这个

// eslint-disable-next-line @typescript-eslint/no-unused-vars

less 提示错误

忽略 less 错误 , 我在antDesign论坛上问的结果

/* stylelint-disable */
:export {
headingColor: @heading-color;
}

1.2. 注释加空格

Expected exception block, space or tab after

// 要加空格,很奇葩,以至于我都想把这个校验给去掉了。

//注释 --这是错误的
// 注释 --这是对的

1.3. 构造函数

报下面的错误:

Use object destructuring. prefer-destructuring

错误用法

let headers = options.headers;

正确用法

let { headers } = options;

1.4. type 的 import

如果要引入的是 type 类型

All imports in the declaration are only used as types. Use import type

错误用法

import { BasicLayoutProps, ProSettings } from '@ant-design/pro-layout';

正确用法

import type { BasicLayoutProps, ProSettings } from '@ant-design/pro-layout';

1.5. i++与 i+=1

不能使用i++,使用下面的语法

i += 1;

1.6. Promise.reject

错误的写法

// 下面esline会提示错误:Expected the Promise rejection reason to be an Error
return Promise.reject('权限组名称重复');

正确的写法

return Promise.reject(new Error('权限组名称重复'));

1.7. 三元运算没必要

错误的写法

memberAvatar ? memberAvatar : ImgFallback;

正确的写法

memberAvatar || ImgFallback;

1.8. 禁止 CSS 的 0 长度

错误的写法

padding-bottom: 0px !important;

正确的写法

padding-bottom: 1px !important;

1.9. 修改参数

例如 ProTable 的 onFinish,会传入一个 vlaues,如果对 values 的内容进行修改。会报错。

Assignment to property of function parameter

正确的做法:

const data = values;

2. React 错误

2.1 避免死循环

由于useState会引发页面刷新,所以要注意以下内容:

  • 如果数据没有填充好,页面显示沙漏
  • 在其他可能引发刷新的hooks中,尽量不使用useState

3. Ant 常见错误

3.1 Table 中 Key 重复

最可能出错的地方是:

  • rowKey拼写错误
  • columns中的render: (_, entity) 渲染的组件,必须要添加 key

不用添加 key 的地方

  • 如果制定了dataIndex 就不用添加 key 了。

3.2 col 中 Key 重复

如果有多个col时,每个 col 都需要添加 key。

另外,如果出现 map 循环输出组件,那么就应该添加一个 key。