2017-01-22 19 views
0

將原始數組作爲道具傳遞,但它似乎被React/jsx修改爲具有鍵的json對象稱爲「0」,「1」等,對應於數組元素。這使得無法確定道具是實際上是一個數組還是單個組件。react - 傳入原始js數組作爲道具,但jsx將其修改爲js對象

例如,

MyComponent的有:

propTypes: { 
     attachedComponents: React.PropTypes.oneOfType([React.PropTypes.array, React.PropTypes.object]) 
    } 

實例化MyComponent的,並通過在陣列中:

var foo = <Foo /> // my custom component 1 
    var bar = <Bar /> // my custom component 2 
    <MyComponent attachedComponents={[foo, bar]} /> 

的問題是,內部MyComponent的,this.props.attachedComponents 不是一個真正的JS數組 - 它是某種具有鍵「0」,「1」的JS對象,每個對象響應傳入的數組元素

這nmakes我不可能以編程方式確定它是否是傳遞在單個元件,或者如果它是一個實際的陣列,而不做一些非常糟糕的kludging:

MyComponent的:

getInitialState: function() { 
     // this cannot work as intended, because the array passed in is converted into a js object whose typeof is object, not array: 
     if (typeof this.props.attachedComponents !== 'array') { 
      // do code for single component situation 
     } 
    } 

我不能檢查Object.keys(this.props.attachedComponents).length,因爲,通過在一個單一的組件,Object.keys(this.props.attachedComponents)看起來是這樣的:

["$$typeof", "type", "key", "ref", "props", "_owner"] 

現在,如果您想知道爲什麼我要傳遞組件數組,那是因爲我想要編程添加組件;我見過this.props.children,但這似乎並不可靠可言:

的Facebook表示,this.props.children是不透明的,則必須使用 React.Children API調用,所有這些都是干將,這似乎 暗示this.props.children不應該變異

關於如何檢測this.props.attachedComponents是否是一個數組,沒有做一些非常糟糕的kludging任何想法?

感謝

回答

0

JSX不會做任何道具。

這實際上只是調用React.createElement的語法糖。 Your code gets converted to

var foo = React.createElement(Foo, null); // my custom component 1 
var bar = React.createElement(Bar, null); // my custom component 2 
React.createElement(MyComponent, { attachedComponents: [foo, bar] }); 

陣列對象和typeof是怪異。typeof someArray總是返回"object"

console.log(typeof []);

測試對於陣列中的正確的方法是使用Array.isArray

console.log(Array.isArray([])); 
 
console.log(Array.isArray({}));


我見過this.props.children,但這似乎並不可靠,在所有

嗯,這是可靠的,它只是不總是返回相同類型的值。有許多幫助功能可用於處理this.props.children。看看React.Children。例如。您可以使用React.Children.toArray(this.props.children)將該值轉換爲真數組。

您在簡單引用中突出顯示的部分意味着您不應該更改this.props.children本身的值。但這在任何方面都不無道理。

+0

謝謝!我被一些愚蠢的JS事物咬了,我想我也曾經犯過這個錯誤。在JS中記住整個堆棧要記住3-4種語言的奇怪怪癖太多了。順便說一句,我的意思是this.props.children是不可靠的,因爲我不確定我可以適當地改變它,以編程方式添加/刪除組件。這就是爲什麼我手動添加組件作爲一個數組,我作爲道具傳入。這可能更好地問作爲另一個問題(!)謝謝! – dev

相關問題