propTypes isRequired约束错误导致反应行为 [英] propTypes isRequired constraint mis-leading behaviour in react

查看:1046
本文介绍了propTypes isRequired约束错误导致反应行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很反应(或说网络技术)。我开始构建一个使用不同组件的应用程序。当我浏览文档时,我想在propTypes中放置 isRequired ,约束用户在使用时提供所有 isRequired 属性组件。

I'm very new to react( or to say web technologies). I started building an app which uses different components. When I went through the documentation, I thought putting isRequired in propTypes, constrains the user to provide all isRequired attributes when using the component.

但是,在这个例子中,即使我没有传递 isRequired 属性,我也能够加载组件。

But, in this example even if I don't pass isRequired attributes I'm able to load the component.

var PanelPreview = React.createClass({
    getInitialState: function(){
       return { captionIndex: 0 };
    },
    propTypes: {
       beforeSrc: React.PropTypes.string.isRequired,
       afterSrc: React.PropTypes.string.isRequired,
       captionTable: React.PropTypes.array
    },
});
module.exports = PanelPreview;

使用此组件的应用程序:

app using this component:

   React.render(
      < PanelPreview />,
      document.getElementById('main')
   );

我想约束组件的用户提供这两个值,否则会引发某种错误。

I want to constrain the user of the component to provide these two values else throw some sort of error.

推荐答案

道具失败验证目前不被视为严重错误。但是在控制台中会记录一个警告:

Props failing validation isn't currently considered a critical error. However there will be a warnning logged in the console:

Warning: Required prop `beforeSrc` was not specified in `PanelPreview`.

这只发生在非生产版本的react中。在生产中没有记录。请参阅此小提琴,以获取示例 http://jsfiddle.net/5mafp3eu/1/

This only happens in a non-production build of react. In production nothing is logged. See this fiddle for an example http://jsfiddle.net/5mafp3eu/1/

一直在讨论如何让React快速失败以进行道具验证失败(请参阅下面的问题),看起来它最终会发生,但我认为它还没有出现在任何路线图上。

There has been discussion about having React fail-fast for prop validation failures (see issues below), it seems like it's going to happen eventually, but I don't think it's on any roadmap yet.

  • https://github.com/facebook/react/issues/1587
  • https://github.com/facebook/react/issues/1753

这篇关于propTypes isRequired约束错误导致反应行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆