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语句。我怎样才能克服这个问题?
截图:
如果我评论if语句:
最初是空数组,取回数据后填写,见下表: