Props 非空检测

对于并非 isRequired 的 proptype,必须对应设置 defaultProps,避免再增加 if 分支带来的负担

  1. // bad
  2. render () {
  3. if (this.props.person) {
  4. return <div>{this.props.person.firstName}</div>
  5. } else {
  6. return <div>Guest</div>
  7. }
  8. }
  1. // good
  2. class MyComponent extends Component {
  3. render() {
  4. return <div>{this.props.person.firstName}</div>
  5. }
  6. }
  7. MyComponent.defaultProps = {
  8. person: {
  9. firstName: 'Guest'
  10. }
  11. }

如有必要,使用 PropTypes.shape 明确指定需要的属性