2017-08-25 80 views
0

尋找關於此的建議或最佳實踐。我做對了嗎?呈現組件中的數組

我減速機:

export default function(){ 
    return [ 
     { 
     id: '01', 
     name: 'Cersei Lannister', 
     city: 'Kings Landings' 
     }, 
     { 
     id: '02', 
     name: 'Margaery Tyrell', 
     city: 'Hign Garden' 
     }, 
     { 
     id: '03', 
     name: 'Daenerys Targaryen', 
     city: 'Dragon Stone' 
     }, 
     { 
     id: '04', 
     name: 'Ygritte', 
     city: 'Free Folk' 
     }, 
     { 
     id: '05', 
     name: 'Arya Stark', 
     city: 'Winter Fell' 
     } 
    ] 
} 

我結合這個減速器中allReducersgotPeople。我在一個組件myApp使用此:

import React, { Component } from 'react'; 
import { Text, View } from 'react-native'; 
import { connect } from 'react-redux'; 

class MyApp extends Component { 

    render(){ 

     const renData = this.props.gotPeople.map((data, idx) => { 
      return (
       <View key={idx}> 
        <Text>{data.id}</Text> 
        <Text>{data.name} of {data.city}</Text> 
       </View> 
      ) 
     }); 

     return(
      <View> 
       {renData} 
      </View> 
     ); 
    } 
} 

function mapStateToProps (state) { 
    return { 
    gotPeople: state.gotPeople 
    } 
} 

export default connect(mapStateToProps)(MyApp) 

當我import MyApp from ./MyApp;在我index.android.js並調用它在View<MyApp />它的工作原理。一切正常顯示。我不確定這是否是正確的方法?有沒有更好的方法?

請指教。

回答

2

你的減速機實際上並不是「減速」,即它不會減少任何東西。但讓我們假設它只是一個用於示例目的的佔位符。在這種情況下,一切看起來不錯,但我會重寫你的組件一點,使其更短:

const MyApp = ({ gotPeople }) => (
    <View> 
    {gotPeople.map((data, idx) => (
     <View key={idx}> 
     <Text>{data.id}</Text> 
     <Text>{data.name} of {data.city}</Text> 
     </View> 
    )} 
    </View> 
); 
+0

謝謝。除了組件的長度,沒有錯誤,對吧?我的意思是我用'{renData}'調用數組中的數據正確嗎? – Somename

+1

@Somename是的,一切都是正確的。 – fkulikov