2015-09-30 44 views
2

下面的代碼創建有序和無序列表。雖然代碼的其他部分不是因爲不相關而張貼在這裏React JS'propTypes'驗證程序運行兩次

問題: 我通過在'Navigation'組件中調用它來將一些屬性傳遞給'List'組件。我通過'List'的propTypes運行一些驗證來驗證'List'收到的項目。但是,我注意到驗證正在運行兩次。我無法弄清楚爲什麼?

是否因爲代碼中發生了一些競態條件。或者,它是否是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); 
+0

你怎麼知道他們正在運行兩次?你看到了什麼輸出? –

+0

@DavinTryon我在'customProp'中設置了一個斷點,並在調用堆棧中遍歷。 – gca

回答

1

您的customProp引用並檢查另一個prop:'type'。如果您需要自定義功能,請在要應用該功能的道具之後放置該功能。

實際上您只需要2個propTypes:type和items。你想確保提供的類型是'ol'或'ul'。
要做到這一點,你不需要第三個propType。

更改propTypes代碼:

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

那麼你不需要你的customProp。然後你的代碼應該做你想做的。

+0

嗯。是的,它的工作原理和感謝。但是這並不能回答我的問題。 customProps不應該進行兩輪驗證。我找到了一些與之相關的文章。 – gca