代码之家  ›  专栏  ›  技术社区  ›  Somename

在组件中渲染阵列

  •  0
  • Somename  · 技术社区  · 8 年前

    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'
          }
        ]
    }
    

    allReducers gotPeople 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 /> 它起作用了。所有内容都正确显示。我不确定这样做是否合适?还有更好的办法吗?

    1 回复  |  直到 8 年前
        1
  •  2
  •   fkulikov    8 年前

    您的减速机实际上看起来不是“减速机”,即它不会减少任何东西。但我们假设它只是一个占位符,用于示例。在这种情况下,一切看起来都很好,不过我会重写您的组件,使其更短:

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