reactjs - 如果不需要 propType 为什么 ESLint 要为其提供默认 prop?

标签 reactjs eslint airbnb-js-styleguide

const propTypes = {
  label: PropTypes.string,
};
const defaultProps = {};

为什么 ESLint 希望我们在不需要时为标签提供默认值?

(react/require-default-props)

我要续订爱彼迎

最佳答案

我得出的结论是,当您可以使用 ES6 默认值时,为组件定义 defaultProps 没有任何有意义的好处。

我发现的唯一好处 ( from the docs ):

One advantage of defaultProps over custom default logic in your code is that defaultProps are resolved by React before the PropTypes typechecking happens, so typechecking will also apply to your defaultProps. The same also holds true for stateless functional components: default function parameters do not behave the same as defaultProps and thus using defaultProps is still preferred.

所以有一些预期的好处,但我认为实现 defaultProps 所需的冗长和时间使它们不值得,除非您确实需要此功能。

<小时/>

异常(exception):

我们确实对一些组件进行了异常(exception)处理并定义了 OurComponent.defaultProps,但即便如此,我们还是有选择地这样做。我们只在原本使用 ES6 默认值的地方定义它们。我们不会为每个非必需的 prop 定义默认值。

值得注意的是,相关规则包含在 eslint-plugin-react 中。 “推荐”配置。

关于reactjs - 如果不需要 propType 为什么 ESLint 要为其提供默认 prop?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52332394/

相关文章:

javascript - 如何使用 Airbnb JavaScript 样式指南设置 Prettier

javascript - 异步请求后如何在路由中重定向?

reactjs - 从 UseContext 值初始化 UseState 值

javascript - react : Switch Case/Same Component doesn't Unmount

javascript - react 使用 dangerouslySetInnerHTML 渲染带有 html 标签的 json

reactjs - .eslintrc.js 用于 React 17 和 JSX,无需导入 'react'

javascript - 带有 Airbnb 风格指南的 ESLint 不适用于所有规则

javascript - 在 React 中使用 map 创建组件

reactjs - Reactjs 中的 EsLint "react/jsx-props-no-spreading"错误禁用