admin管理员组文章数量:1430077
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?
- You should design an app that doesn't pass invalid types to your ponents ;) – Andy Ray Commented Dec 7, 2016 at 20:52
2 Answers
Reset to default 5You 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!
本文标签: javascriptChecking prop types in ReactStack Overflow
版权声明:本文标题:javascript - Checking prop types in React - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745555854a2663179.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论