笨拙不等待异步功能结束redux

时间:2020-03-05 17:06:14

标签: reactjs redux redux-thunk

我试图对我们的项目实施thunk,但未能使其与异步调用一起使用。 从调试中可以看到,该代码调用API,在返回结果之前请求并使用空数据进行分派。我能想到的唯一问题是我没有正确定义重击。

按照我的代码。

我将其添加到商店中

let Store;
if (NODE_ENV == 'dev'){
    const { composeWithDevTools } = require('redux-devtools-extension');

 Store = createStore(
            connectRouter(history)(Reducers),
            composeWithDevTools(
                applyMiddleware(
                    thunk, 
                    routerMiddleware(history)
                ),
            )
        )
    } else {
        Store = createStore(
            connectRouter(history)(Reducers),
            compose(
                applyMiddleware(
                    thunk,
                    routerMiddleware(history)
                ),
            )
        ); 
    }

将主干添加到操作中:

export function restartSearchAds(is_bookmark){
    console.log('outside')
    return dispatch => {
        console.log('inside')
        const searchParams = getInitSearchParams(is_bookmark);
        dispatch({
            type: AdsType.ADS.RESET_SEARCH_PARAMS,
            searchParams,
            page:1
        });
        dispatch(searchAds(searchParams, 1));
    }
}

export function searchAds(searchParams, page, token, dosearch=0) {
    //logic to get data filters....
    let data = qs.stringify(searchData);

    return function(dispatch){
        return new Promise((res,rej) =>{
            api.doSearch(data)
            .then(ads => {
                page == 1
                ? dispatch({type: AdsType.ADS.LOADED_DEFAULT_ADS, ads: ads, isOffers:false})
                : dispatch({type: AdsType.ADS.ADD_ADS_RESULT, ads: ads, finished: false});
            });
        })
    };
}

还将发布api请求功能:

export async function doSearch(data){
    axios({
        url: //the url,
        method: 'post',
        data: data
    }).then(function(result) {
        if (result.data.status == "ok") {
            let ads = [];
            for (let key in result.data.data.adObj) {
                ads = result.data.data.adObj[key];
            }
            return ads;     
        } else {
            return [];
        }
    }, function (error) {
        console.error(error);
        return [];
    });
}

如果有人知道,请告诉我。 谢谢, 或者

0 个答案:

没有答案