我正在开发一个简单的React Native iOS应用程序,只是为了学习React Native,这是我的第一个React Native应用程序。现在,我正在练习使用ListView。但是似乎项目已加载到列表视图中,但未显示数据。
这是我的减速器
import * as AlbumListActions from '../actions/AlbumListActions';
const defaultState = {
albums: [ ],
loading: false,
message: null
}
export default albumListReducer = (state = defaultState, action) => {
switch (action.type) {
case AlbumListActions.ALBUMS_START_FETCHING_ALBUMS:
return { ...state, loading: true, albums: [ ] }
break;
case AlbumListActions.ALBUMS_COMPLETE_FETCHING_ALBUMS:
return { ...state, loading: false, albums: action.payload }
break;
case AlbumListActions.ALBUMS_CATCH_FETCHING_ALBUMS:
return { ...state, loading: false, message: action.payload }
break;
default:
return { ...state };
}
}
这是我的动作
import Axios from 'axios';
export const ALBUMS_START_FETCHING_ALBUMS = "(albums) start fetching albums";
export const ALBUMS_COMPLETE_FETCHING_ALBUMS = "(albums) complete fetching albums";
export const ALBUMS_CATCH_FETCHING_ALBUMS = "(albums) catch fetching albums";
export const completeFetchingAlbums = (data) => {
return {
type: ALBUMS_COMPLETE_FETCHING_ALBUMS,
payload: data
}
}
export const catchFetchingAlbums = (data) => {
return {
type : ALBUMS_CATCH_FETCHING_ALBUMS,
payload: data
}
}
export const fetchAlbums = (data) => {
return (dispatch) => {
dispatch({
type: ALBUMS_START_FETCHING_ALBUMS
});
return Axios.get("http://rallycoding.herokuapp.com/api/music_albums").then((response) => {
dispatch(completeFetchingAlbums(response.data));
}).catch((error) => {
dispatch(catchFetchingAlbums("Unable to fetch data from the server"));
})
}
}
这是我的组件渲染列表视图。
class AlbumList extends React.Component {
componentWillMount() {
this.props.fetchAlbums();
}
renderAlbumItem = (album) => {
return (
<View style={styles.container}>
<Text>{album.title}</Text>
</View>
)
}
render() {
return (
<View>
<FlatList
data={this.props.albums}
renderItem={this.renderAlbumItem}
keyExtractor={(album) => album.title}
/>
</View>
)
}
}
const mapStateToProps = state => {
return state.albumList;
}
const mapDispatchToProps = (dispatch, ownProps) => {
return bindActionCreators({
fetchAlbums : AlbumListActions.fetchAlbums
}, dispatch)
}
export default connect(mapStateToProps, mapDispatchToProps)(AlbumList);
运行我的应用程序时,它没有显示任何内容。有什么问题,我该如何解决?
答案 0 :(得分:1)
renderItem
的签名是错误的。它接受一个对象,其属性之一是item
,其中包含您要渲染的相册。
要使其正常运行,请按以下方式更改renderItem
:
renderAlbumItem({item}) => {
return (
<View style={styles.container}>
<Text>{item.title}</Text>
</View>
)
}
您还可以将item
重命名为album
-renderAlbumItem({item: album})
。这种语法称为对象解构,您可以在Google上进行解释。在这种情况下,请使用{album.title}
访问标题。