简体   繁体   English

eslint-plugin-react/require-render-return 用于功能组件

[英]eslint-plugin-react/require-render-return for functional components

Unfortunately eslint-plugin-react/require-render-return works only for Class components.不幸的是 eslint-plugin-react/require-render-return 仅适用于 Class 组件。 It does not work for functional components, at least on my end.它不适用于功能组件,至少在我这边。

Why do I need this?为什么我需要这个?

Consider the following example:考虑以下示例:

const Component = () => <div />

The above functional component returns an empty div.上述功能组件返回一个空的 div。

Now consider that we may have to add a hook:现在考虑我们可能需要添加一个钩子:

const Component = () => {
   useEffect(() => { /* some side-effect here */ } );
   <div />
}

So while switching the arrow function from bodyless to having a function body, the developer forgets to return the DOM and the function returns nothing.因此,当将箭头函数从无体切换到有函数体时,开发人员忘记return DOM,函数什么也不返回。 The only way to catch this regression is during code review, which involves the human factor, and this could be missed.捕捉这种回归的唯一方法是在代码审查期间,这涉及人为因素,这可能会被遗漏。 It would be better if there was a linter rule.如果有一个 linter 规则会更好。

So what do you guys do?那么你们是做什么的呢?

This is a perfect example of why you should use TypeScript and not plain old JavaScript.这是一个完美的例子,说明了为什么你应该使用 TypeScript 而不是普通的旧 JavaScript。 It would throw an error at compile/write time pointing to that problem.它会在编译/写入时抛出指向该问题的错误。

const SomeComponent: React.FC = () => <div />
// ✅

const AnotherComponent: React.FC = () => {
  useEffect(() => {})
}
// 💥 "Type 'void' is not assignable to type 'ReactElement<any, any> | null'."

React combined with TypeScript really is the best in every possible way. React 与 TypeScript 的结合在所有可能的方面确实是最好的。 I cannot emphasize enough that you should absolutely learn TypeScript, it is worth every second of your time.我不能强调你绝对应该学习 TypeScript,每一秒都是值得的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM