我正在从API端点获取数据。我已经为VenueList.js采取了行动和简化措施
venueAction.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:
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:
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);
如果我在VenueList.js中取消注释if语句,那么它将显示this.props.venues.data[0].highlight
数据,但是如果没有if语句,则它将引发错误。从API端点获取数据后如何显示数据。最初在获取venues
时未定义,并且在1秒钟后使用api端点填充了数据。所以如果我想显示
<Text>{this.props.venues.data[0].highlight}</Text>
引发错误是否需要在每个部分添加if语句。我该如何克服这个问题?
屏幕截图:
答案 0 :(得分:1)
您可以在尝试访问它之前确保已定义它,并在加载时呈现其他文本。
{this.props.venues ? this.props.venues.data[0].highlight : "Text to display when not loaded"}