使用
useState
钩子时,两个解构数组变量通常采用以下形式:foo
和 setFoo
。
偏离此模板的一些示例是:
const [foo, setfoo] = useState();
const [foo, updateFoo] = useState();
const [foo, fooSetter] = useState();
在代码审查期间,我建议将上面的示例更改为:
const [foo, setFoo] = useState();
有没有一种方法可以针对这种情况进行静态检查(ESLint)?
是的,通过 eslint-plugin-react
您想要的规则是这个:https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/hook-use-state.md
来自文档:
此规则检查从 React.useState() 调用解构的 value 和 setter 变量是否对称命名。
正确示例:
import React from 'react';
export default function useColor() {
// useState call is destructured into value + setter pair whose identifiers
// follow the [thing, setThing] naming convention
const [color, setColor] = React.useState();
return [color, setColor];
}
在您的配置中:
...
"react/hook-use-state": [<enabled>, { "allowDestructuredState": <boolean> }]
...
绝对比在代码审查期间进行监管要好:)