简体   繁体   中英

How to validate props with propTypes having defaultProps?

Earlier when we were not using defaultProps, we use to get warning in the console that this props is not passed. But after configuring the props signature using defaultProps we don't get any errors as such. So, how to configure both to work as expected?

/* Default Props */
MyApp.defaultProps = {
  data: {
    totalCount: 123
  },
  name: 'john doe'
};

/* Proptypes */
MyApp.proptypes = {
  data: {
    totalCount: Proptypes.number.isRequired
  },
  name: Proptypes.string.isRequired
};
import PropTypes from 'prop-types';

You must use

class test { 
    static propTypes = { 
        optionalBool: PropTypes.bool,
        requiredProperty: PropTypes.number.isRequired
}}

You are already doing it correctly, the problem you had before is that when the component was initialized, it had null values for its props, so you get run time warning expecting some null value props, default props sets that value even on initial component mount. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM