2

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

问题:我通过在“导航”组件中调用它来将一些属性传递给“列表”组件。我正在通过“列表”的 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);
4

2 回答 2

2

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

对此作出反应 Github 问题

关于 propValidation 的 React v0.11 博客

于 2015-10-02T18:31:39.727 回答
1

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

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

将 propTypes 代码更改为:

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

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

于 2015-10-01T12:46:52.997 回答