如何在React组件中显示来自api的数据 [英] How to display data from api in react component

查看:142
本文介绍了如何在React组件中显示来自api的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用axios从API获取数据,并且检索到的数据已成功分发到商店,目前在将数据显示在React组件中存在一些问题.

I am using axios to get data from an API and the retrieved data was successfully dispatched to the store, I currently have some problems in displaying the data in my React component.

我能够成功地console.log数据,但事实证明,在从API完全检索数据之前,我的组件已呈现.

I was able to console.log the data successfully but it turns out my component renders before the data was fully retrieved from the API.

以下是显示数据的组件:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { bindActionCreators } from 'redux';
import HeaderSidebar from './includes/header-navbar';
import AllBooks from './includes/all-books';
import { getAllBooks } from '../../actions/book_actions';


class AdminHome extends Component {

componentDidMount() {
    this.props.actions.getAllBooks();
}

renderBooks(){
    const allbooks = this.props.books;

    return allbooks.map((book) => {
        return (<div key={book.id}>
            <AllBooks title={book.title}
            description={book.description}
            />
        </div>)
    })
}
render() {
    return (
        <div >
            <HeaderSidebar />
          {this.renderBooks()}
            })}
            })}
        </div >
    )
  }
}

  function mapStateToProps(state) {
    return {
    books: state.book.data
  }
}

 AdminHome.PropTypes = {
  books: PropTypes.object.isRequired
}

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators({
        getAllBooks
    }, dispatch)
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(AdminHome);

操作

export function getAllBooks() {
  return dispatch => axios.get(`${API_URL}`)
    .then((res) => {
      dispatch({
        type: GET_ALL_BOOKS,
        data: res.data
      });
      return res.data;
    })
    .catch(error => error);
}

减速器 导入{ADD_BOOK, GET_ALL_BOOKS },来自"../actions/types";

Reducers import { ADD_BOOK, GET_ALL_BOOKS } from '../actions/types';

const INITIAL_STATE = {};

function bookReducer(state = INITIAL_STATE, action) {
  switch (action.type) {
    case ADD_BOOK:
      return { ...state, message: 'Book added Successfully' };
    case GET_ALL_BOOKS:
      return { ...state, data: action.data };
    default:
      return state;
  }
}

export default bookReducer;

推荐答案

在数据加载完成之前,您可以显示其他内容

You can show something else until the data is done loading

renderBooks(){
if(!this.props.books) {
  return (<p>Loading data..<p/>);
}


// rest of your code here 

或者您可以使用一个空数组初始化该属性,以便在完成数据加载之前至少没有崩溃.

Or you can initialize the property with an empty array so that at least nothing crashes until the data is done loading.

function mapStateToProps(state) {
  return {
    books: state.book.data || []  //  maybe have to extra checks here if state.book doesn't exist yet
}

(或同时执行两个操作,将if(!this.props.books)更改为if(this.props.books.length < 1).

(Or do both, and change if(!this.props.books) to if(this.props.books.length < 1).

这篇关于如何在React组件中显示来自api的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆