在组件中渲染数组

时间:2017-08-25 06:40:17

标签: react-native redux react-redux

寻找有关此建议或最佳做法。我做得对吗?

我的减速机:

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 个答案:

答案 0 :(得分: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>
);