首页 > 解决方案 > React Native:从获取的 JSON 数据中填充 FlatList 并过滤数据以根据数据类型呈现特定图标

问题描述

我很难弄清楚如何将 RN 组件与我从 API 获取的数据一起使用。

获取的数据如下所示:

fetchDataActionCreator {
"isFetching": false,
"items": {
  "user1": [
    {
      "from": "home address",
      "to": "destination address",
      "cost": "8.95",
      "tripNo": "1234",
    },
    {
      "from": "random address",
      "to": "home address",
      "cost": "10",
      "tripNo": "1235",
    },
  ]
  "user2": [
    {
      "from": "home address",
      "to": "destination address",
      "cost": "8.95",
      "tripNo": "4321",
    },
    {
      "from": "random address",
      "to": "home address",
      "cost": "10",
      "tripNo": "4322",
    },
  ]
}

}

这是我的 Redux 结构中用于检索 JSON 数据的操作创建函数:

function fetchDataActionCreator(users) {
return function(dispatch) {
  dispatch(requestDataActionCreator());

  const reqs = users.map(user => {
    /* [{from, to, cost}] */
    return getData(users.userId.toLowerCase(), user.number);
  });

  return Promise.all(reqs).then(allHistory => {
    /* [{from, to, cost}] */

    const res = {};
    for (let i = 0; i < allHistory.length; i++) {
      res[users[i].userId] = allHistory[i];
    }

    dispatch(receiveDataActionCreator(res));
  });
};

}

下面是组件的代码

    import React, {Component} from 'react';
import {Text, View, Fragment, FlatList, ListItem, Icon, RefreshControl} from 'react-native';

renderItem = ({
    item: { to, from, cost},
  }) => (
    <ListItem title={}>
      <Fragment>
        <View>
            <Icon name={}/>
        </View>
        <Text>To address: {to}</Text>
        <Text>From address: {from}</Text>
        <Text>Cost: {cost}</Text>
      </Fragment>
    </ListItem>
  );

  keyExtractor = ({ tripNo }) => tripNo;

  filterTrips = () => {

  };

class History extends Component {
  render() {
    const { isLoading, onRefresh } = this.props;

    const filteredTxs = this.filterTxs();
    return (
      <View>
          <FlatList
            data={filteredTxs}
            keyExtractor={this.keyExtractor}
            renderItem={this.renderItem}
            refreshControl={<RefreshControl refreshing={isLoading} onRefresh={onRefresh} />}
          />
      </View>
    );
  }
}

const mapStateToProps = state => {
  return {
    history: state.fetchDataActionCreator,
  };
};

export default connect(mapStateToProps)(History);

我尤其在这些事情上遇到困难:

任何关于我如何实现这一点的指导都将非常感激,因为我对 React/React Native 还是很陌生。

标签: javascriptreactjsreact-nativereact-redux

解决方案


推荐阅读