使用flatlist而不是scrollview

时间:2017-04-07 11:47:51

标签: react-native react-native-flatlist

我有以下代码,它工作正常我可以连接到API并获取数据,因为我得到了一个庞大的线程列表如何使用Flatlist重构代码?

谢谢

import React, { Component } from 'react';
import { ScrollView } from 'react-native';
import axios from 'axios';
import ThreadDetail from './ThreadDetail';

class TopicList extends Component {
  state = {
    threads: []
  };

  componentWillMount() {
    axios.get('https://xxxxxxx.devmn.net/api/v1/forums/threads?topic_id=2418', {
      headers: {
        'client-id': 'a0f21e'
      }
    })
      .then(response => this.setState({ threads: response.data.threads }));
  }

  renderThreads() {
    return this.state.threads.map(thread =>
      <ThreadDetail key={thread.thread.id} thread={thread.thread} />
    );
  }

  render() {
    return (
      <ScrollView style={styles.listStyle}>
        {this.renderThreads()}
      </ScrollView>
    );
  }
}

const styles = {
  listStyle: {
    backgroundColor: 'purple'
  }
}

export default TopicList;

1 个答案:

答案 0 :(得分:0)

export default class TopicList extends Component {

     constructor() {
           super(props);

           this.state = {
                threads: []
           }
     }

     componentWillMount() {
           .... // same as your code
     }

     renderItem({index, item}) {
           return <ThreadDetail thread={item.thread} />
     }

     render() {
          return <View>
                     <FlatList 
                         data={this.state.threads}
                         renderItems={this.renderItem}
                         keyExtractor={(item, index) => item.thread.id} />
                 </View>
     }
}

注意:我没有测试过这个