[英]How to display data after getting complete data from API endpoint in react native?
I am fetching data from API endpoint.我正在从 API 端点获取数据。 I have made action and reducer for VenueList.js
我为 VenueList.js 做了 action 和 reducer
venueAction.js:场地动作.js:
import { FETCH_VENUES } from './types';
import axios from 'axios';
export const fetchVenues = () => dispatch => {
axios.get(`API_ENDPOINT`)
.then( venues =>
dispatch({
type: FETCH_VENUES,
payload: venues
})
)
.catch( error => {
console.log(error);
});
};
venueReducer.js:场地Reducer.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;
}
}
VenueList.js:场地列表.js:
import React, { Component } from 'react';
import { View } from 'react-native';
import { connect } from 'react-redux';
import { fetchVenues } from '../actions/venueAction';
class VenueList extends Component {
componentWillMount (){
this.props.fetchVenues();
}
render() {
// if(this.props.venues.data){
console.log(this.props.venues.data[0].highlight)
// }
return (
<View style={styles.container}>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1
},
});
const mapStateToProps = state => ({
venues: state.venues.items
})
export default connect (mapStateToProps, { fetchVenues })(VenueList);
If I uncomment the if statement in VenueList.js then it shows the this.props.venues.data[0].highlight
data but if there is no if statement then it throws error.如果我取消对 VenueList.js 中的 if 语句的注释,则它会显示
this.props.venues.data[0].highlight
数据,但如果没有 if 语句,则会引发错误。 How can I display data after getting the data from API endpoint.从 API 端点获取数据后如何显示数据。 Initially during fetch
venues
are undefined and after 1 sec the data is filled in using api endpoint.最初在提取期间未定义
venues
,1 秒后使用 api 端点填充数据。 So if I want to display所以如果我想显示
<Text>{this.props.venues.data[0].highlight}</Text>
it throws error Do I need to add if statements at each sections. <Text>{this.props.venues.data[0].highlight}</Text>
它抛出错误我是否需要在每个部分添加 if 语句。 How can I overcome this issue ?我怎样才能克服这个问题?
Screenshots:截图:
if I comment the if statement:如果我评论 if 语句:
Initially venues is empty array and after fetch the data is filled in see below:最初场地是空数组,获取数据后填写如下:
您可以在尝试访问它之前确保它已定义,并在加载时呈现一些其他文本。
{this.props.venues ? this.props.venues.data[0].highlight : "Text to display when not loaded"}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.