defaultProps或默认参数

发布于:2021-02-03 14:50:20

0

3395

0

javascript defaultProps 默认参数

当您在React组件中使用默认参数设置默认属性时,您不会得到proptypes验证,而且您还需要在要使用这些属性的每个类方法中定义这些默认参数。

最近,在我所做的代码回顾中,我在React组件中看到了这样的代码:

render() {
 const {
   count = 0
 } = this.props;
 return{ count }}


我的第一个想法是,这是错误的,因为您应该通过添加名为defaultProps的属性或使用静态方法来定义默认道具。

// Setting a defaultProps property
class App extends React.Component {
 render() {
   const {count} = this.props;
   return{count}}
}
App.defaultProps = {
 count: 0
}

// Adding an static method to the component
class App extends React.Component {
 static defaultProps = {
   count: 0
 }
 render() {
   const {count} = this.props;
   return{count}}
}

但在尝试了代码之后,令我惊讶的是,它成功了!所以我想知道这在React组件中是否是一个有效的实践,因为我在任何地方都没有见过它。即使这样做是可行的,也有一些事情是行不通的,但它们并不是那么明显。

PropTypes验证

根据React文档:propTypes类型检查发生在defaultProps解析之后,因此类型检查也将应用于defaultProps。

这意味着,在定义proptypes时,将在props和默认props中进行验证,这些props和默认props是使用static defaultPropsdefaultProps方法设置的,而不是使用默认参数设置的。

例如,如果我们这样做:

class App extends React.Component {
 render() {
   const { count } = this.props
   return{ count }}
}

App.propTypes = {
 count: PropTypes.number
}

App.defaultProps = {
 count: 'hello'
}


我们将收到以下警告:

index.js:1446 Warning: Failed prop type: Invalid prop `count` of type `string` supplied to `App`, expected `number`.


但是如果我们使用默认参数:

class App extends React.Component {
 render() {
   const { count = 'hello' } = this.props
   return{ count }}
}

App.propTypes = {
 count: PropTypes.number
}

我们不会得到任何错误或警告,因为React没有任何方法进行运行时分析。

类方法之间的props值可能不一致

当我们定义defaultProps时,它内部定义的值将在React组件中的每个方法上可用,但如果我们使用defalt参数,则必须在每个方法上定义默认值。让我举个例子来解释一下。

class App extends React.Component {
 componentDidMount() {
   const { count } = this.props
   console.log('count in CDM: ', count)
 }
 render() {
   const { count } = this.props
   console.log('count in Render: ', count)
   return{ count }}
}

App.propTypes = {
 count: PropTypes.number
}

App.defaultProps = {
 count: 10
}

如果运行此代码,我们将得到:

count in Render:  10
count in CDM:  10

如您所见,在每个方法上,默认值都是相同的,因此我们可以确定,如果没有传递prop,则所有地方的默认值都是相同的。

相反,如果使用默认参数,则每个类方法的属性可能不同。

class App extends React.Component {
 componentDidMount() {
   const { count } = this.props
   console.log('count in CDM: ', count)
 }
 render() {
   const { count = 10 } = this.props
   console.log('count in Render: ', count)
   return{ count }}
}

App.propTypes = {
 count: PropTypes.number
}

在本例中,我们将得到以下结果:

count in Render:  10
count in CDM:  undefined

在组件的不同部分对同一道具使用不同的值是非常糟糕的。

最后的想法

这类事情提醒我,几乎总是有可能编写出正确的代码,因此我们需要了解编写应用程序时所做决策的影响。这可以看作是一个小组件的问题,当您可以随时关注正在发生的一切时,但是一旦应用程序变得更大,就很难跟踪这种bug。