如何在反应组件中显示来自api的数据

时间:2017-09-10 17:24:21

标签: node.js reactjs axios

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

我能够成功console.log数据,但在从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);
}

减速     import {ADD_BOOK,       GET_ALL_BOOKS     来自'../ 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;

1 个答案:

答案 0 :(得分:3)

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

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


// rest of your code here 

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

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)