处理Redux商店中的承诺/回调

时间:2017-04-11 02:53:40

标签: javascript reactjs redux

我目前正在使用Redux的动作创建程序来调度用户操作(例如,获取帐户信息)。这些操作创建者从API请求中返回promise,当他们解析时,更新商店。

我遇到的问题是我想“拦截”来自API的某些响应,在我的例子中,是一个无效的JWT令牌。在这种情况下,我想保留待处理的承诺,提示登录模式,如果登录成功,则重新获取并解决承诺。

以这种方式呼叫fetch后,我就可以检查回复了:

Root.js - 将Modal组件放入DOM

export default (props) => {
    return (
        <div>
            <Modal />
            <App />
        </div>
    )
}

Modal.js - 处理不同的模态类型(从this post采用的方法)

const MODALS = {
    LOGIN: LoginModal
}

const ModalRoot = ({type, props}) => {
    if (!MODALS[type]) return null;

    return <Modal {...props} />;
}

export default connect(
    state => state.modal
)(ModalRoot);

reducer.js - 模态缩减器

const initialState = {type: null, props: {}}
export default function modal(state = initialState, action) {
    switch (action.type) {
        case 'SHOW_MODAL':
            return Object.assign({}, state, {
                type: action.modalType,
                props: {...action.props}
            });
        case 'HIDE_MODAL':
            return initialState;
        default:
            return state;
    }
}

actions.js - 返回获取电话的承诺

const promptLogin = () => (dispatch, getState) => {
    return new Promise((resolve, reject) => {
        return dispatch(showModal('LOGIN', {
            successCallback: (user) => resolve(user)
        }));
    })
}

makeAPIRequest.js - 进行API调用,处理无效令牌

fetch(endpoint, requestConfig)
    .then(res => res.json())
    .then(data => {

        /** Invalid JWT Token */
        if (data && data.error_code === 403) {
            return store.dispatch(promptLogin())
                .then(token => {
                    return makeRequest(method, endpoint, headers, body)
                });
        }

        return data;
    });

这种方法的问题在于我将持久的回调函数(为了完成初始请求)到商店,这在redux文档中是不鼓励的。

如果我的模态组件没有连接到我的获取逻辑,并且我无法在状态中存储Promise或回调(因为它们不可序列化),我怎样才能在初始请求后继续承诺用户从模态执行登录?

0 个答案:

没有答案
相关问题