2017-04-07 71 views
1

我有下面的代碼,它工作正常我可以連接到API並獲取數據,因爲我得到一個巨大的線程列表我該如何重構使用Flatlist的代碼呢?使用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; 
+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> 
    } 
} 

注:我沒有測試過這

+0

我在iOS模擬器中遇到錯誤'不能讀取未定義的屬性'索引',@BrainYoung –

+0

我的代碼看起來像這樣https://jsbin.com/jakojuhomo/edit?js當我遇到'index'錯誤時未定義。 @Brain Young –

+0

@AlbertoFerioli你能告訴我你的線索數據是如何構成的嗎? 'response.data.threads' –