React Native - 渲染列表

时间:2017-10-08 09:27:54

标签: reactjs react-native

我有以下代码段:

import React, { Component } from 'react';
import { View, Text } from 'react-native';
import axios from 'axios';
import AlbumDetail from './AlbumDetail';

class AlbumList extends Component {
    state = { albums: [{}, {}, {}] };

    componentWillMount() {
        //console.log('componentWillMount in AlbumList');
        axios.get('https://rallycoding.herokuapp.com/api/music_albums')
            .then(response => this.setState({ albums: response.data }));
    }

    renderAlbums() {


        this.state.albums.map(album => {


            return (


                <Text key={album.title}>{album.title}</Text>
            );
        });
    }

    render() {
        const movies = this.state.albums.map(album => {


            return (

                <Text key={album.title}>{album.title}</Text>

            );
        });

        return (
            <View>
                {movies}
                {this.renderAlbums()}

            </View>
        );
    }
}

export default AlbumList;

电影列表应打印两次,一次是因为movies变量,另一次是因为renderAlbums()调用。但是它只打印一次,因为movies变量。 renderAlbums()不起作用。有什么想法吗?

1 个答案:

答案 0 :(得分:4)

您也需要在returnrenderAlbums

renderAlbums() {
   return this.state.albums.map(album => {
        return (
            <Text key={album.title}>{album.title}</Text>
        );
    });
}