Как получить данные в ответ на редукс - PullRequest
0 голосов
/ 23 марта 2020

Я не понимаю, почему я сначала получаю неопределенные, а после этого я получаю правильные данные, в том числе и потому, что я не определен в componentDidMount (), я не могу собирать данные здесь, поэтому, если кто-то знает, как решить эту проблему, пожалуйста, помогите мне, также я использую инструменты redux-dev и там я получаю правильные данные, но здесь, на консоли, я получаю данные, как я пишу ниже

action. js

import * as actionTypes from '../actions/actionTypes';

export const fetchToursSuccess = ( tours ) => {
    return {
        type: actionTypes.FETCH_TOURS_SUCCESS,
        tours: tours
    };
};

export const fetchToursFail = ( error ) => {
    return {
        type: actionTypes.FETCH_TOURS_FAIL,
        error: error
    };
};

export const fetchToursStart = () => {
    return {
        type: actionTypes.FETCH_TOURS_START
    };
};


export const fetchTours = () => {
    return dispatch => {
        dispatch(fetchToursStart());
            fetch('http://localhost:5000/api/v1/tours')
            .then(response => {
                if (response.status !== 200) {
                  throw new Error('Failed to fetch tours.');
                }
                return response.json();
            })
            .then( resData => {
                const fetchedTours = [];
                for ( let key in resData.data.data ) {
                    fetchedTours.push( {
                        ...resData.data.data[key],
                        id: key
                    } );
                }
                console.log(fetchedTours);
                dispatch(fetchToursSuccess(fetchedTours));
            } )
            .catch( err => {
                dispatch(fetchToursFail(err));
            });
    };
};

reducer. js

import * as actionTypes from '../actions/actionTypes';
import { updateObject } from '../utility';

const initialState = {
    tours: [],
    loading: false,
    isLoaded: false,
};

const fetchToursStart = ( state, action ) => {
    return updateObject( state, { loading: true } );
};

const fetchToursSuccess = ( state, action ) => {
    return updateObject( state, {
        loading: false,
        isLoaded: true,
        tours: action.tours

    } );
};

const fetchToursFail = ( state, action ) => {
    return updateObject( state, { loading: false } );
};

const reducer = ( state = initialState, action ) => {
    switch ( action.type ) {
        case actionTypes.FETCH_TOURS_START: return fetchToursStart( state, action );
        case actionTypes.FETCH_TOURS_SUCCESS: return fetchToursSuccess( state, action );
        case actionTypes.FETCH_TOURS_FAIL: return fetchToursFail( state, action );
        default: return state;
    }
};

export default reducer;

Обзор компонентов. js

import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';

// import axios from '../../axios-orders';

import * as actions from '../store/actions/index';
import { fetchTours } from '../store/actions/tour';

class Overview extends Component {
    componentDidMount () {
        console.log( this.props.onFetchTours());
        console.log( this.props.tours);
    }

    render () {
        if ( this.props.loading ) {
            console.log('Loading..........');
        }


        return (
            <div>
                hello from Overview
            </div>
        );
    }
}

const mapStateToProps = state => {
    return {
      tours: state.tours,
      loading: state.loading,
      isLoaded: state.isLoaded

    };
  };

const mapDispatchToProps = dispatch => {
    return {
        onFetchTours: () => dispatch( actions.fetchTours() )
    };
};


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

я получаю следующие результаты,

Overview.js:12 undefined
Overview.js:13 []
Overview.js:49 Loading..........
tour.js:131 (9) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
Overview.js:53 (9) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...