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/