首页 > 解决方案 > 在反应类组件方法中等待完成 redux-saga

问题描述

如果这是一个重复的问题,我很抱歉,但我已经搜索了这个问题,但没有找到完全解决我的问题的答案。我想在 sagas 中获取数据并在获取数据localStorage后进行更新。然后我想this.forceUpdate()在我的组件方法中。但显然this.forceUpdate()功能是在加载数据之前启动的。我可以将我的handleSubmit类方法包装成 promise 或 async/await 以this.forceUpdate()等待获取数据吗?谢谢你。

FETCHING FUNCTION

export const fetchAuth = data => {
    return axios({
        method: "post",
        url: "http://url/",
        headers: {},
        data: {
            email: data.email,
            password: data.password.toString()
        }
    }).then(response => {
        return response.data;
    });
};

REDUX-SAGA

export function* authRequestFlow(action) {
    try {
        const tokens = yield call(fetchAuth, action.payload);
        if (tokens) {
            yield call(save, "access", tokens.access);
            yield call(save, "refresh", tokens.refresh);
            yield call(save, "isAuthorized", true);
            yield put(authSuccess());
        }
    } catch (error) {
        yield put(authFailure(error.message));
    }
}

COMPONENT

class Login extends PureComponent {
    handleSubmit = () => {
        authRequest();
        this.forceUpdate();
    };

    render() {
        if (localStorage.getItem("isAuthorized") === "true")
            return <Redirect to="/products" />;
        return (
            <div className={styles.root}>
                    <Button
                        onClick={this.handleSubmit}
                    >
                        Submit
                    </Button>
            </div>
        );
    }
}

标签: reactjsasync-awaitfetchredux-saga

解决方案


推荐阅读