最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Checking prop types in React - Stack Overflow

programmeradmin0浏览0评论

I was reading the React.Component section in the official React documentation. Everything made sense except for the part regarding propTypes. The docs state the following:

In production mode, propTypes checks are skipped for efficiency.

Say I have the following code:

class Sample extends React.Component {
    render() {
        return (
            <div>Hello {this.props.name}</div>
        );
    }
}

Sample.propTypes = {
    name: React.PropTypes.string
};

Does the docs imply that in production my type checks against props will be skipped? If yes, how should I be checking prop types?

I was reading the React.Component section in the official React documentation. Everything made sense except for the part regarding propTypes. The docs state the following:

In production mode, propTypes checks are skipped for efficiency.

Say I have the following code:

class Sample extends React.Component {
    render() {
        return (
            <div>Hello {this.props.name}</div>
        );
    }
}

Sample.propTypes = {
    name: React.PropTypes.string
};

Does the docs imply that in production my type checks against props will be skipped? If yes, how should I be checking prop types?

Share Improve this question asked Dec 7, 2016 at 20:46 AmousAmous 5145 silver badges18 bronze badges 1
  • You should design an app that doesn't pass invalid types to your ponents ;) – Andy Ray Commented Dec 7, 2016 at 20:52
Add a ment  | 

2 Answers 2

Reset to default 5

You don't check against the prop types yourself at all, React does that for you.

However, as the docs say, only as long as you are in development mode. Every prop type check is essentially a function call that uses processing power and memory.


While you are in development, knowing that one of your props has the wrong type makes this cost a worthy trade-off.

Once you are in production, your app should be tested thoroughly enough already that none of your prop type validations fail anymore anyway.

For this reason, they are skipped to make your app a bit more efficient instead.

propTypes are only used to verify your current development process. You get notified via console logs when some required properties are missing, or the type of a property doesn't match the expected one.

There is no need to verify this type of validation in production builds. Missing properties don't break the rendering process, they just render your ponent in an unexpected way. But notice that your rendering process will fail, when you need to access properties of an "given" object.

To get in control over this unexpected behaviour, you should declare default properties.

However, working with the propTypes object and using unit tests is highly remended to avoid unexpected rendering behaviour. Stick with it!

发布评论

评论列表(0)

  1. 暂无评论