繁体   English   中英

分派后调用函数? (Redux)

[英]Call function after dispatch? (Redux)

我正在使用Firebase开发一个React应用程序。 我想在dispatch完成后调用第一个函数。 每个用户都被分配了一个currentcity ,但是我不希望currentcity被删除,因为那样会破坏应用程序。 所以我想做的是在调用deleteCity函数之后运行changeCurrentCity函数,以免发生这种情况。 我只是想将currentcity分配给列表中的第一个。

changeCurrentCity()不从内运行.then()deleteCity 我尝试过console.log-ing它,它只是显示功能本身。 我敢肯定这只是一个简单的解决方法,但我不知道自己在做什么。

const changeCurrentCity = (city) => {
    return (dispatch, getState, { getFirebase, getFirestore }) => {
        const firestore = getFirestore();
        const userId = getState().firebase.auth.uid;
        firestore.collection('users').doc(userId).update({
            currentcity: city
        }).then(() => {
            dispatch({ type: 'UPDATE_CITY', city });
        }).catch((err) => {
            dispatch({ type: 'UPDATE_CITY_ERROR', err});
        })
    }
};

const deleteCity = (city) => {
    return (dispatch, getState, { getFirebase, getFirestore }) => {
        const firestore = getFirestore();
        firestore.collection('cities').doc(city.id).delete().then(() => {
            dispatch({ type: 'DELETE_CITY', city });
        }).then(() => {
            changeCurrentCity(getState().firestore.data.cities[Object.keys(getState().firestore.data.cities)[0]].userid);
        }).catch((err) => {
            dispatch({ type: 'DELETE_CITY_ERROR', err});
        })
    }
};

export {changeCurrentCity, deleteCity}

问题出在deleteCity 删除城市后, changeCurrentCity未运行。

调度动作是异步的,这就是为什么可能在调度后立即调用changeCity而不更新存储的原因。 您可以使用asnyc等待发送,然后解决承诺。 这将延迟changeCity直到完成删除。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM