即使devtools中的网络选项卡显示API调用状态为200

时间:2017-06-14 17:13:23

标签: javascript api asynchronous redux react-redux

我是redux的新手,我很难理解如何将API调用的有效负载连接到我的状态。

现在我的action.js文件如下所示:

import ApiService from '../../services/ApiService';
import { reset } from 'redux-form';

//actions
export const getStock = () => {
  return {
    type: 'GET_STOCK'
  }
}

export const getStockPending = () => {
  return {
    type: 'GET_STOCK_PENDING'
  }
}

export const getStockFulfilled = (stock) => {
  return {
    type: 'GET_STOCK_FULFILLED',
    payload: stock 
  }
}

export const getStockRejected = () => {
  return {
    type: 'GET_STOCK_REJECTED'
  }
}

// async function calls

export function fetchStocksWithRedux() {
  const action_type = "GET_STOCK";
  const stock = 'AAPL';
    return (dispatch) => {
    dispatch({type: `${action_type}_PENDING`});
    return ApiService.get(`/search?query=${stock}`)
    .then(([response, json]) =>{
        if(response.status === 200){
        dispatch(getStockFulfilled(json))
      }
      else{
        dispatch(getStockRejected())
      }
    })
  }
}

我的reducer.js文件如下所示:

const initialState = {
  inProgress: false,
  stock: {},
  stocks: ['NKE', 'AMZN', 'AAPL'],
  error: {}
}

export default (state = initialState, action) => {
  switch(action.type) {

    case 'GET_STOCK_PENDING': 
      return {
        ...state, 
        inProgress: true,
        error: false
      }

    case 'GET_STOCK_FULFILLED': 
      return {
        ...state,
        stock: action.payload,
        inProgress: false
      }

    case 'GET_STOCK_REJECTED': 
      return {
        ...state,
        inProgress: false,
        error: action.error
      }
    default: 
      return state;
  }
}

当我在我的组件中调用我的方法fetchStocksWithRedux时,我的开发工具中的网络选项卡显示200状态和我期望的响应,但是reducer调度' GET_STOCK_REJECTED'动作,但错误哈希是空的。你觉得怎么回事?

这是我的组件,供参考:

import React, { Component } from 'react';
import { fetchStocksWithRedux } from '../../redux/modules/Stock/actions';
import { connect } from 'react-redux';

class Dashboard extends Component {

    componentDidMount() {
       this.props.fetchStocksWithRedux()
    }

    render() {
        return (
            <div className="uk-position-center">

            </div>
            )
        }
    }

export default connect(
  state => ({
    stocks: state.stocks,
    stock: state.stock
  })
  , { fetchStocksWithRedux }
)(Dashboard);

感谢。任何建议或指导将不胜感激!

0 个答案:

没有答案