React JS ' proptype '验证器运行两次

React JS 'propTypes' validators running twice

本文关键字:两次 验证 JS proptype React 运行      更新时间:2023-09-26

下面的代码创建有序和无序列表。虽然其他部分的代码没有张贴在这里,因为不相关

问题:我通过在"导航"组件中调用它来传递一些属性给"列表"组件。我通过运行一些验证通过'List'的propTypes来验证'List'收到的项目。然而,我注意到验证运行了两次。我不知道为什么?

是因为代码内部发生了一些竞争条件吗?或者,这是React中的一个bug ?

var Navigation = React.createClass({
   render: function() {
      return (
         <nav>
            <List type="ol" items={this.props.items} />
         </nav>
      );
   }
});
var List = React.createClass({
   propTypes: {
      type: React.PropTypes.string.isRequired,
      items: React.PropTypes.array.isRequired,
      customProp: function(props, propName, componentName) {
        if (props["type"] !== "ol" && props["type"] !== "ul") {
           return new Error("Incorrect list type provided");
        }
      }
   },
   getInitialState: function() {
      return {
         showList: true,
         listType: this.props.type
      }
   },
   render: function() {
      return (
         <this.state.listType>
            {this.props.items.map(function(item) {
               return <ListItem data={item} />
            })}
         </this.state.listType>
      )
   }
});
React.render(<Navigation items={items} />, document.body);

这是因为React在0.11中引入了描述符这个问题在v0.12中仍然存在。下面的链接详细介绍了这一点。

React Github issue on this

React v0.11 blog on propValidation

您的customProp引用并检查另一个prop: 'type'。如果你需要一个自定义函数,把它放在你想要应用该函数的道具之后。

你实际上只需要2个propTypes: type和items。您需要确保提供的类型为'ol'或'ul'。
要做到这一点,不需要第三个propType。

将propTypes代码更改为:

propTypes: {
  type: React.PropTypes.oneOf(['ol', 'ul']),
  items: React.PropTypes.array.isRequired
},

那么你不需要你的customProp。然后你的代码应该做你想做的。