尝试使用axios.get()检索数据,但Promise似乎永远不会返回

时间:2018-10-31 18:19:52

标签: reactjs redux get axios

我目前正在尝试使用对https://jsonplaceholder.typicode.com的获取请求来更新Redux减速器,我可以从笔记本电脑上卷曲该站点,但是当我尝试从应用程序中获取axios.get(URL / data)时,数据永远不会被记录下来,所以我认为承诺永远不会回来?我在代理后面,但是为代理配置了NodeJ,因此不确定我是否必须将一些额外的数据传递给与代理相关的axios或不执行外部GET请求。基本上,应用逻辑应如下所示:

GET Data from site with axios and is logged in firefox web console->reducer is passed payload from GET-> reducer fills each object in data into an array->View updated listing all objects in array on screen with the .map function.

以下是获取数据并更新商店的化简器:

import axios from 'axios';

import { SUCCESS } from 'app/shared/reducers/action-type.util';

export const ACTION_TYPES = {
  GET_APP_COMMENTS: 'applicationComments/GET_COMMENTS'
};

const initialState = {
  postId: 1,
  id: 1,
  name: 'testname',
  email: 'testemail',
  body: 'body'
};

export type ApplicationCommentsState = Readonly<typeof initialState>;

    export default (state: ApplicationCommentsState = initialState, action): ApplicationCommentsState => {
      switch (action.type) {
        case SUCCESS(ACTION_TYPES.GET_APP_COMMENTS):
          const { data } = action.payload;
          return {
            ...state,
            postId: data.postId,
            id: data.id,
            name: data.name,
            email: data.email,
            body: data.body
          };
        default:
          return state;
      }
    };

    export const getComments = () => ({
      type: ACTION_TYPES.GET_APP_COMMENTS,
      payload: axios.get('https://jsonplaceholder.typicode.com/comments')
      .then(res => {
        console.log('got here' + res);
      })
    });

我在Redux index.js文件中设置了这个化简器,在其中合并了所有化简器:

import { combineReducers } from 'redux';
import { loadingBarReducer as loadingBar } from 'react-redux-loading-bar';

import authentication, { AuthenticationState } from './authentication';
import applicationProfile, { ApplicationProfileState } from './application-profile';
import applicationComments, { ApplicationCommentsState } from './application-comments'; // Is this the correct way to import the comments reducer?

import administration, { AdministrationState } from 'app/modules/administration/administration.reducer';
import userManagement, { UserManagementState } from 'app/modules/administration/user-management/user-management.reducer';
import register, { RegisterState } from 'app/modules/account/register/register.reducer';
import activate, { ActivateState } from 'app/modules/account/activate/activate.reducer';
import password, { PasswordState } from 'app/modules/account/password/password.reducer';
import settings, { SettingsState } from 'app/modules/account/settings/settings.reducer';
import passwordReset, { PasswordResetState } from 'app/modules/account/password-reset/password-reset.reducer';

export interface IRootState {
  readonly authentication: AuthenticationState;
  readonly applicationProfile: ApplicationProfileState;
  readonly applicationComments: ApplicationCommentsState;
  readonly administration: AdministrationState;
  readonly userManagement: UserManagementState;
  readonly register: RegisterState;
  readonly activate: ActivateState;
  readonly passwordReset: PasswordResetState;
  readonly password: PasswordState;
  readonly settings: SettingsState;
  /* jhipster-needle-add-reducer-type - JHipster will add reducer type here */
  readonly loadingBar: any;
}

const rootReducer = combineReducers<IRootState>({
  authentication,
  applicationProfile,
  applicationComments,
  administration,
  userManagement,
  register,
  activate,
  passwordReset,
  password,
  settings,
  /* jhipster-needle-add-reducer-combine - JHipster will add reducer here */
  loadingBar
});

export default rootReducer;

我在以下组件中调用作为道具传递的getComments方法,这应该触发console.log,但不会触发,并且组件无论如何都将呈现:

import './appView.css';

import React from 'react';
import { Link } from 'react-router-dom';
import { CommentsSection } from './appView-componets';
import { connect } from 'react-redux';
import { Container } from 'reactstrap';

import { getSession } from 'app/shared/reducers/authentication';
import { getComments } from 'app/shared/reducers/application-comments';

export interface IAppViewState {
  dropdownOpen: boolean;
}

export interface IAppViewProp extends StateProps, DispatchProps, IAppViewState {}

export class AppView extends React.Component<IAppViewProp> {
  state: IAppViewState = {
    dropdownOpen: false
  };

  componentDidMount() {
    this.props.getSession();
    this.props.getComments();
  }

  toggleCatagories = () => {
    this.setState({ dropdownOpen: !this.state.dropdownOpen });
  };

  render() {
    const comments = this.props;
    console.log('comments: ' + comments);
    return (
      <div>
        <CommentsSection comments={comments} />
      </div>
    );
  }
}

const mapStateToProps = storeState => ({
  account: storeState.authentication.account,
  isAuthenticated: storeState.authentication.isAuthenticated,
  comments: storeState.applicationComments.comments
});

const mapDispatchToProps = { getSession, getComments };

type StateProps = ReturnType<typeof mapStateToProps>;
type DispatchProps = typeof mapDispatchToProps;

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

2 个答案:

答案 0 :(得分:0)

有支持Redux的库,如RxJs(Observables),Redux Saga,Redux Thunk以及与Redux集成的其他库,它们也可用于处理动作并与axios结合与后端对话。如果您只想使用axios(用于直接调用服务器的库),则必须包装该调用,以便您首先分派ex。 GET_COMMENTS_START操作,没有有效负载(可能是URL),并且在reducer内,您可以使用axios调用服务器。解决axios承诺后,您应该执行另一个操作,例如GET_COMMENTS_SUCCESS,该操作将返回将成为所需有效负载的数据,然后您可以通过props进行检索。 这种方法可能有效,但是您应该使用Redux特定的库,例如ReduxThunk或RxJs,因为代码更加一致和可维护。 有用的链接:

  1. https://rxjs-dev.firebaseapp.com/
  2. https://redux-saga.js.org/
  3. https://github.com/reduxjs/redux-thunk

答案 1 :(得分:0)

我在我的应用中尝试了该请求,它似乎运行良好。我不确定您是否已正确设置操作以使用thunk中间件。也许试试看。

export const getCommentSuccess = (comments) => {
    return {
        type: ACTION_TYPES.GET_APP_COMMENTS,
        comments
    }
}

export const getComments = () => {
    return function(dispatch) {
        return axios.get('https://jsonplaceholder.typicode.com/comments').then(response => {
            console.log(response) //This should be the returned comments
            dispatch(getCommentSuccess(response));
        }).catch(error => {
            throw(error);
        });
    };

并确保您的中间件已正确导入商店中。

import thunkMiddleware from 'redux-thunk';

const store = createStore(rootReducer, 
    applyMiddleware(
        thunkMiddleware
    )
);