1

我有以下代码,它工作正常我可以连接到 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;
4

1 回答 1

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

注意:我没有测试过这个

于 2017-04-07T13:02:08.223 回答