2017-06-16 133 views
1

我有一個包含數組的組件,並且我想將該數組傳遞給子組件,並使用map根據該數組的元素渲染項目。但是,當試圖使用數組映射時,React似乎無法將數組識別爲prop,因爲我得到以下錯誤:作爲道具傳遞給子組件時,React Native Array不起作用

未定義不是對象('Evaluating this.props.foodTagList.map' )

所以它認爲地圖是一個對象,而不是一個功能...

總之,家長:

const food = { TagList:[ 
    { 
     TagId: 4, 
     TagName: "onion" 
    }, 
    { 
     TagId: 6, 
     TagName: "beef" 
    }, 
    { 
     TagId: 7, 
     TagName: "pork" 
    }, 
    { 
     TagId: 8, 
     TagName: "carrot" 
    }, 
    { 
     TagId: 9, 
     TagName: "fish" 
    } 
]}; 

<FoodTags foodTagList={food.TagList} /> 

與子女:

export default class FoodTags extends React.Component{ 

constructor(props){ 
    super(props); 
} 

shouldComponentUpdate(nextProps, nextState){ 
    return false; 
} 

render(){ 
    return <View style={layoutStyles.tagWrapper}> 
     {this.props.foodTagList.map((x, i) => { 
      return(<Tag key={i} info={this.props.foodTagList[i]} />) 
     })} 
    </View> 
} 

}

class Tag extends React.Component{ 
constructor(props){ 
    super(props); 
} 

render(){ 
    return <Text style={foodStyles.tag}>{this.props.info.TagName}</Text> 
} 

}

所以我的問題是真的:我如何正確地傳下去陣列子組件?

+0

這是我在寫這個問題時犯的一個錯誤。它不在我的代碼中,顯然不是錯誤的根源。問題依然存在。當我將數組作爲道具傳遞時,孩子不再將其視爲數組。 順便說一下。使用x [i]而不是this.props.foodTagList [i]也不起作用。 –

+0

你是從服務器獲取數據還是硬編碼?不要使用'info = {this.props.foodTagList [i]}'使用'info = {x}'索引對於x不是必需的。 –

+0

「所以它認爲地圖是一個對象,而不是一個功能......」不,它認爲'this.props.foodTagList'是'undefined'。指定'FoodTags'組件的屬性類型'static propTypes = {foodTagList:PropTypes.array.isRequired}'來查看哪個組件傳遞了不正確的道具。 –

回答

0

我感覺foodTagList實際上是undefined當你最初渲染,因爲你有return false你根本沒有得到數據。如果它認爲map是一個對象而不是函數,你會得到Uncaught TypeError: map is not a function或類似的東西。您可以嘗試在shouldComponentUpdate內返回true

+0

shouldComponentUpdate在這種情況下不是問題。 –

相關問題