javascript - react native 从 API 端点获取完整数据后如何显示数据?
问题描述
我正在从 API 端点获取数据。我为 VenueList.js 做了动作和减速器
场地Action.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);
});
};
场地减速器.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;
}
}
地点列表.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 语句。我该如何克服这个问题?
截图:
解决方案
您可以确保在尝试访问它之前对其进行定义,并在加载时呈现一些其他文本。
{this.props.venues ? this.props.venues.data[0].highlight : "Text to display when not loaded"}
推荐阅读
- eclipse - 在 Eclipse 中启动 Tomcat 服务器时出现 404
- cakephp - CK 编辑器编辑页面未显示 youtube 嵌入代码
- python - 字典变量和“for”循环
- javascript - 如何通过文本输入使全局变量可变
- c++ - 避免在循环中使用 if 条件的最佳方法是什么?
- java - 通过调用 FCM 推送通知 api 时出错
- python - 如何从支持 Python 2 和 Python 3 的代码中调用 unittest.assertRaisesRegex?
- azure-devops - Azure Devops:计划的服务请求
- python - 如何让我的 Spyder 代码在 GPU 而不是 Ubuntu 上的 cpu 上运行?
- android - 如何更改 Drawable 的颜色?