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

React JS 'propTypes' validators running twice

下面的代码创建有序和无序列表。虽然其他部分代码因为无关紧要就不贴在这里了

问题: 我通过在 'Navigation' 组件中调用它来将一些属性传递给 'List' 组件。我正在通过 运行 验证 'List' 收到的项目,通过 'List' 的 propTypes 进行一些验证。但是,我注意到验证是 运行 两次。我不知道为什么?

是不是因为代码内部发生了一些竞争条件。或者,它是 React 中的错误吗?

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);

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

您实际上只需要 2 个 propType:类型和项目。您要确保提供的类型是 'ol' 或 'ul'.
为此,您不需要第三个 propType。

将 propTypes 代码更改为:

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

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

这是因为React在0.11引入了描述符 这个问题在 v0.12 中仍然存在。下面的链接对此进行了更多讨论。

React Github issue on this

React v0.11 blog on propValidation