首页 > 解决方案 > 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 语句。我该如何克服这个问题?

截图:

如果我评论 if 语句: 在此处输入图像描述

最初场地是空数组,在获取数据后填写如下: 在此处输入图像描述

标签: javascriptreactjsreact-native

解决方案


您可以确保在尝试访问它之前对其进行定义,并在加载时呈现一些其他文本。

{this.props.venues ? this.props.venues.data[0].highlight : "Text to display when not loaded"}

推荐阅读