Catalogue of this series

  • 01 preface
  • 02 Development environment construction
  • 03 Scaffolding creates projects where everything is a component
  • 04 Basic features JSX, Props, State, Lifecycle, Event, and Style
  • Component rendering control
  • 06 Container components, display components
  • 07 Front-end route react-router
  • 08 State management React-Redux
  • 09 Data request fetch
  • 10 Check the attribute type prop-types

Liking is a virtue:)


React Quick start – check PropTypes for 10 types

The target

  • Understand the importance of type checking
  • Use and debug type checking
  • Some tips for type checking

The environment

  • The react 16.3.2
  • Prop – types 15.6.1

Why do we need type checking

Let’s take a look at rollbar’s top10 error recovery analysis for 1000+ projects

Top 10 JavaScript errors from 1000+ projects

Almost always because of the type

For example, define let prodList = [], prodlist.push (…) in your code.

But initially with prodList = 123 set and no prompt, run push(…) Be sure to report unknown method errors

This kind of problem is common in the free JavaScript world, where if there is no prompt at both compile and run stages, the troubleshooting is cumbersome, and it’s all a matter of experience and familiarity with the business (old projects without documentation can be hell).

So we nipped the issue in the bud by defining the types when we declared the objects. React’s own solution is the PropTypes component

And of course Flow TypeScript. I personally like TypeScript. I’ll write about that in a more advanced post

PropTypes is a scheme that provides type checking during the coding phase and it’s always good to have a hint, so let’s get started

PropTypesuse

As usual, let’s start with a basic, simple example

1. Simple Examples

  • Import packages
import PropTypes from 'prop-types'
Copy the code
  • Write a component
class Greeting extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>}}Copy the code
  • Writing type checks
Greeting.propTypes = {
  name: PropTypes.string
}
Copy the code

Set the name attribute type to string

  • The container
<div>
  <Greeting name={123} />
</div>
Copy the code

Obviously, the number is not the same as the definition

  • Pages to print

The page displays normally, with no errors, because errors are reported in the console mode

  • A page fault

All right, just a hint

2 Different validators

// Array, Boolean, function, number, object, string, symbol
MyComponent.propTypes = {
  optionalArray: PropTypes.array,
  optionalBool: PropTypes.bool,
  optionalFunc: PropTypes.func,
  optionalNumber: PropTypes.number,
  optionalObject: PropTypes.object,
  optionalString: PropTypes.string,
  optionalSymbol: PropTypes.symbol,

  // Anything can be rendered :numbers, strings, elements, or an array (or fragment) containing these types.
  optionalNode: PropTypes.node,

  // A React element.
  optionalElement: PropTypes.element,

  // You can also declare a prop to be an instance of a class.
  // Use the JS instanceof operator.
  optionalMessage: PropTypes.instanceOf(Message),

  // You can declare prop to be a specific value, similar to an enumeration
  optionalEnum: PropTypes.oneOf(['News'.'Photos']),

  // An object can be one of many types
  optionalUnion: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.number,
    PropTypes.instanceOf(Message)
  ]),

  // An array of some type
  optionalArrayOf: PropTypes.arrayOf(PropTypes.number),

  // The value of the property is an object of a certain type
  optionalObjectOf: PropTypes.objectOf(PropTypes.number),

  // An object of a particular form
  optionalObjectWithShape: PropTypes.shape({
    color: PropTypes.string,
    fontSize: PropTypes.number
  }),

  // You can link any of the above using 'isRequired' to ensure that warnings are displayed when no prop is provided.
  requiredFunc: PropTypes.func.isRequired,

  // Value of any data type
  requiredAny: PropTypes.any.isRequired,

  // You can also declare custom validators. If validation fails, an Error object is returned. Do not use 'console.warn' or throw,
  // Because this does not work in validators of type 'oneOfType'.
  customProp: function(props, propName, componentName) {
    if (!/matchme/.test(props[propName])) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        '` + componentName + '`. Validation failed.'); }},// You can also declare validators of types' arrayOf 'and' objectOf 'and return an Error object if validation fails.
  // The validator is called on each element of an array or object. The first two arguments to the validator are either the array or the object itself,
  // And the key of the current element.
  customArrayProp: PropTypes.arrayOf(function(propValue, key, componentName, location, propFullName) {
    if (!/matchme/.test(propValue[key])) {
      return new Error(
        'Invalid prop `' + propFullName + '` supplied to' +
        '` + componentName + '`. Validation failed.'); }})};Copy the code

3 limits single progeny

code

// component const OnlyOneChild = props => {const children = props. Children return <div>{children}</div>} OnlyOneChild.propTypes = { children: PropTypes. Element. IsRequired} / / container < OnlyOneChild > < h3 > the first child node < / h3 > < h3 > second child node < / h3 > < / OnlyOneChild >Copy the code

print

4 Default values for properties

code

/ / component
const DefaultVal = props= > {
  return <h3>{props.name}</h3>
}
DefaultVal.defaultProps = {
  name: 'I'm the default! '
}

/ / container
<div>
  <DefaultVal />
</div>
Copy the code

If the parent component does not set it and passes in a name, defaultProps ensures that this.props. Name will have a default value.

print

code

  • 8-propTypes.js

reference

  • Top 10 JavaScript errors from 1000+ projects
  • prop-types

© Cat that makes coffee