我创建了VenueList组件。我想在React Native应用程序中使用FlatList组件显示列表。我收到错误消息:Invariant Violation试图使帧超出范围索引(请参见屏幕截图)。
代码:
VenueList.js:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { View, Text, FlatList, StyleSheet } from 'react-native';
import { connect } from 'react-redux';
import { fetchVenues } from '../actions/venueAction';
class VenueList extends Component {
componentWillMount () {
this.props.fetchVenues();
}
renderItem = ({ item }) => (
<View style={styles.item}>
<Text>{item.attributes.name}</Text>
</View>
);
render() {
return (
<FlatList
styles={styles.container}
data={this.props.venues}
renderItem={this.renderItem}
/>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1
},
item: {
padding: 16,
borderBottomWidth: 1,
borderBottomColor: '#ccc'
}
});
VenueList.propTypes = {
fetchVenues: PropTypes.func.isRequired,
venues: PropTypes.array.isRequired
}
const mapStateToProps = state => ({
venues: state.venues.items
})
export default connect (mapStateToProps, { fetchVenues })(VenueList);
venueReducer.js:
import { FETCH_VENUES } from '../actions/types';
const initialState = {
items: []
}
export default function (state = initialState, action) {
switch (action.type) {
case FETCH_VENUES:
return {
...state,
items: action.payload
};
default:
return state;
}
}
venueAction.js:
import { FETCH_VENUES } from './types';
import axios from 'axios';
export const fetchVenues = () => dispatch => {
axios.get(`my_api_link`)
.then( venues =>
dispatch({
type: FETCH_VENUES,
payload: venues
})
)
.catch( error => {
console.log(error);
});
};
我要从API端点显示的数据具有json数据,如下所示:
{
"data": [
{
"type": "venues",
"id": "nb",
"attributes": {
"name": "Barasti Beach",
"description": "Barasti Beach is lotacated in the awesome barasti beach",
"price_range": "$$$",
"opening_hours": "10:30-12:40/16:00-2:00",
"organization": {
"id": "GD",
"legal_name": "Barasti",
"brand": "Barasti"
},
"place": {
"address": "Le Meridien Mina Seyahi Beach Resort & Marina, Dubai Marina - Dubai - United Arab Emirates",
"latitude": "25.092648",
"location": [
"Marina Bay",
"Dubai",
"Arab Emirate United"
]
}
}
}
],
"meta": {
"total": 1,
"cursor": {
"current": 1,
"prev": null,
"next": null,
"count": 25
}
}
}
请参见下面的屏幕截图:
答案 0 :(得分:1)
根据上述针对 api 请求的回复,
问题出在操作中设置的payload
上。您需要将数据从api传递到Flatlist
,因为它仅接受数组。
axios.get(`my_api_link`)
.then( venues =>
dispatch({
type: FETCH_VENUES,
payload: venues.data
})
)
编辑:
添加VenueList.js
组件(如果api在data
键内返回值):
renderItem = ({ item }) => (
<View style={styles.item}>
<Text>{item.attributes.name}</Text>
</View>
);
render() {
return (
<FlatList
styles={styles.container}
data={this.props.venues.data}
renderItem={this.renderItem}
/>
);
}