關於 React 小書:PropTypes 和 Component 參數驗證


Posted by YongChenSu on 2020-12-09

isRequired

已設定參數驗證但傳入非指定參數會提供較為友善的錯誤訊息

import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import PropTypes from 'prop-types'

class Comment extends Component {
  static propTypes = {
    comment: PropTypes.object.isRequired
  }

  render () {
    const { comment } = this.props
    return (
      <div className='comment'>
        <div className='comment-user'>
          <span>{comment.username} </span>:
        </div>
        <p>{comment.content}</p>
      </div>
    )
  }
}

ReactDOM.render(
  <Comment comment={1} />,
  document.getElementById('root')
)



PropTypes 和 Component 參數驗證

PropTypes.array
PropTypes.bool
PropTypes.func
PropTypes.number
PropTypes.object
PropTypes.string
PropTypes.node
PropTypes.element


PropTypes 參數驗證的優點

  1. 因錯誤訊息會提供更詳細的資訊,幫助 debug,雖然撰寫上會稍微麻煩一點點,但非常推薦使用 PropTypes 驗證參數。
  2. 在 Component 的開發、使用規範更明確。

參考資源


#程式導師實驗計畫第四期 #前端 #React #react 小書 #propTypes







Related Posts

[InfluxDB] 使用 Telegraf + Prometheus 監控 InfluxDB 效能

[InfluxDB] 使用 Telegraf + Prometheus 監控 InfluxDB 效能

Privacy Policy

Privacy Policy

DE2_115(DAY3)以niosii去控制板子上的sdram

DE2_115(DAY3)以niosii去控制板子上的sdram


Comments