2016-08-01 73 views
0

我有一個反應組件,比如說component_1。 而且,我的數組的格式爲array_list = [{},{},{},{}]。呈現數組中的多個反應組件

我試圖呈現此組件在我的另一個組件,component_2,就像這樣:

import component_1 from 'component_1' 
import array_list from 'array_list' 

class component_2 extends Component{ 
    constructor(props){ 
    super(props) 
    } 

    render(){ 
    const {renderMenu} = this.props 
    var contentData = []; 
    array_list.forEach(function(item, index, array){ 
      contentData.push(<component_1 {...item} />); 
    }); 
    return(
     <div> 
     <div className="ui four column centered grid"> 
      {contentData} 
     </div> 
     </div> 
    ) 
    } 
} 

export default component_2 

同時,它通常與其他HTML元素的作品。在這裏它會拋出一個錯誤:

React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components). Check the render method of `OnBoardingContentElement` 

可以渲染反應組件的數組這樣嗎?如果不是,那麼是否有任何規避方法?

回答

0

您確定您的導入聲明正在工作嗎?同樣可以看看array.map,它非常適合將對象數據數組轉換爲組件數組。

+0

哪個導入語句?我假設你在談論array_list,它是的,然後答案是否定的,它不會工作。這只是一個sudo代碼。我在函數內部創建了array_list。 – nitte93user3232918

+0

不,您的組件導入。如果createElement抱怨null,那麼它聽起來像你的組件沒有被正確導入。 – John

0

這是@ John的回答。

昨晚我遇到了這個確切的問題。這是我在做什麼:

// MyComponent.js 

export const MyComponent = (<h1>Hello, world</h1>); 

// index.js 

import { MyComponent } from './MyComponent'; 

React.render((<MyComponent />), document.getElementById('root')); 

你能看到錯誤嗎?它有點微妙。

問題是MyComponent.js未導出React組件。它導出已經實例化的React元素。

@約翰建議這可能是你在做什麼。糾正它的最好方法是確保MyComponent.js實際上是導出組件:

// MyComponent.js 

export const MyComponent =() => (<h1>Hello, world</h1>);