Reputation: 189
I'm working my way through a React Native tutorial and have run into an issue. I created a class based component that shows a small list on the screen by mapping an array to 5 text components. This worked find. When I replace the text component with a function based component I'm running into issues. I'm fetching the data for the array in componentWillMount, when I switch to the function based component I'm seeing componentWillMount being called repeatedly and no data is being show on the screen. The render method is also being called repeatedly. I'm using react native 0.50.
AlbumList.js:
//Import libraries for making registerComponent
import React, { Component } from 'react';
import { View, Text } from 'react-native';
import axios from 'axios';
import AlbumDetail from './AlbumList';
class AlbumList extends Component {
constructor(props) {
super(props);
this.state = { albums: [] };
}
componentDidMount() {
console.log('componentDidMount in AlbumList');
axios.get('https://rallycoding.herokuapp.com/api/music_albums')
.then(
response => this.setState({ albums: response.data })
);
}
renderAlbums() {
return this.state.albums.map(
//album => <AlbumDetail key={album.title} album={album} />
album => <Text key={album.title}>{album.title}</Text>
);
}
render() {
console.log(this.state.albums);
return (
<View>
{this.renderAlbums()}
</View>
);
}
}
export default AlbumList;
AlbumDetail.js:
//Import libraries for making registerComponent
import React from 'react';
import { Text, View } from 'react-native';
const AlbumDetail = (props) => {
return (
<View>
<Text>{props.album.title}</Text>
</View>
);
};
export default AlbumDetail;
index.js:
import React from 'react';
import { AppRegistry, View } from 'react-native';
import Header from './src/Components/Header';
import AlbumList from './src/Components/AlbumList';
const App = () => (
<View>
<Header headerText={'Albums'} />
<AlbumList />
</View>
);
AppRegistry.registerComponent('albums', () => App);
When mapping to the component everything works as expected. When mapping to the component componentWillMount and render are getting called in a seemingly infinite loop. I tried componentDidMount with the same results.
Upvotes: 1
Views: 1033
Reputation: 189
I figured out what happened. I made a silly mistake and imported AlbumList into itself and it was recursively mounting itself.
import AlbumDetail from './AlbumList';
Should've be
import AlbumDetail from './AlbumDetail';
Upvotes: 0
Reputation: 10719
Try this:
renderAlbums() {
const list = this.state.albums.map(album => {
return <AlbumDetail key={album.title} album={album} />;
});
return list;
}
Upvotes: 1