React redux触发两个动作

时间:2017-07-27 18:02:46

标签: javascript reactjs asynchronous redux

我在使用react redux和异步调用时遇到了一些问题。 当我调用我的api它返回ok并调度正确的动作然后由于某种原因我没有看到,之后会调用其他一些动作。 api课程如下。

class StockApi{
/**
 * function to call the api to search data
 * @param {string} nameofStock stock code to searchs
 * @param {string} startdate start date for search
 * @param {string} enddate end date for search
 */
static getStock(nameofStock,startdate,enddate){
    return new Promise((resolve,reject)=>{
        fetch(`http://localhost:5000/api/data/stocksearch?stockName=${nameofStock}&startdate=${startdate}&enddate=${enddate}`)
        .then(response=>{
            return response.json();
        })
        .then(result=>{
            console.log("result: " + JSON.stringify(result));
            //return result;
            resolve(result);

        })
        .catch(error=>{
            console.log('There has been a problem with your fetch operation: ' + error.message);
            //return {isDataOK:false,ErrorInfo:error,resultData:{}};
            //reject(error.message)
            throw new Error(error.message);
        });
    });

}

}
export default StockApi;

定义的行动:

import StockApi from '../api/stocksApi';
    import * as types from '../constants/Actiontypes';

    export const requestDataStocks = value => ({
      type: types.REQUEST_STOCKS,
      value
    })
    export const recieveData=result=>({
        type:types.RECIEVE_STOCKS,
        result
    })

    export const recieveDataNOK=error=>({
        type:types.RECIEVE_STOCKS_NOK,
        error

    })

    /**
     * "private" function to process the request information
     * 
     */
    const fetchData=stockData=>dispatch=>{

        dispatch(requestDataStocks(stockData));
        StockApi.getStock(stockData.stockName,stockData.startDate,stockData.endDate)
                .then((result)=>{

                    console.log("item got here: data is ok");
                    dispatch(recieveData(result));

                })
                .catch((err)=>{
                    console.log("got here: data is nok: "+ err);
                    dispatch(recieveDataNOK(err));
                });
    }

    /**
     * checks the state to see if the date exists
     * @param {*} state the state of the app
     * @param {object} stockData information to be searched
     */
    const shouldGetDataStock=(state,stockData)=>{

        if (!state.items){
            console.log("no items");
            return true;
        }
        const datainState=state.items.find(x=>x.searchIndex===stockData.stockName+stockName.startDate+stockName.endDate);

        if (!datainState){
            return true;
        }
        if (datainState.isSearching){
            return false;
        }
        return datainState.didInvalidate;

    }
    /**
     * entry point operation for searching data
     * @param {object} stockData data to be searched
     */
    export const fetchStocksIfNeeded=stockData=>(dispatch, getState)=>{

        if (shouldGetDataStock(getState(),stockData)){
            return dispatch(fetchData(stockData));
        }
    }

减速器:

    import {REQUEST_STOCKS,
    RECIEVE_STOCKS,RECIEVE_STOCKS_NOK,
    SET_STOCK_VALUE,
    SET_DATA_START,
    SET_DATA_END
} from '../constants/Actiontypes'

const StockAppReducer= (state = {
    isSearching:false,
    didInvalidate:false,
    stockQuery:'',
    initialDate:'',
    finalDate:'',
    items: []
}, action) => {
    switch (action.type) {  
        case REQUEST_STOCKS:
            console.log("reducer REQUEST_STOCKS: "+action.value);
            return {
                ...state,
                isSearching: true,
                didInvalidate: false,
            }
            break;

        case RECIEVE_STOCKS:
            console.log("reducer RECIEVE_STOCKS: "+action.result.stockName);    
            return {
                ...state,
                items: [...state.items, {searchIndex: action.result.stockCode+"-"+action.result.stockQueryStart+"-"+action.result.StockQueryEnd,searchResults:action.result}],
                isSearching:false,
                didInvalidate:false,
                stockQuery:'',
                initialDate:'',
                finalDate:''
            }
            break;
        case RECIEVE_STOCKS_NOK:
            console.log("reducer RECIEVE_STOCKS_NOK: \n error: "+ action.error);
            return{
                ...state,
                isSearching:false,
                didInvalidate:false,
                isSearching:false,
                didInvalidate:false,
                stockQuery:'',
                initialDate:'',
                finalDate:''
            }
            break;


        default:
            return state;

    }

};





export default StockAppReducer;

Actiontypes.js文件

export const REQUEST_STOCKS='REQUEST_STOCKS';
export const RECIEVE_STOCKS='RECIEVE_STOCKS';
export const RECIEVE_STOCKS_NOK='RECIEVE_STOCKS_NOK';
export const INVALIDATE_STOCK='INVALIDATE_STOCK';
export const SET_DATA_START='DATA_START';
export const SET_DATA_END='DATA_END';
export const SET_STOCK_VALUE='STOCK_SET';

所以基本上fetchData被称为没有问题。 但是当promise从api解析时,它会正确地调度动作,因为我可以看到它被记录:

  

项目到此处:数据正常

传递给reducer然后我可以在reducer上(通过console.log)看到RECIEVE_STOCKS动作被处理,RECIEVE_STOCKS_NOK声明如下:

  

错误:ReferenceError:未定义StockInformation

我的代码中没有任何股票信息或任何信息。我检查过并仔细检查过,没有参考。

有人可以提供一些帮助吗?实际上可能是什么问题?

0 个答案:

没有答案