首页 > 解决方案 > 使用 react-redux 和 react-aad-msal 登录后如何触发操作?

问题描述

我创建了一个使用 react-redux 和react-aad-msal来处理 AD 登录的应用程序。我可以毫无问题地登录和注销,但是在用户登录后,我想触发 API 调用以从 API 获取数据。我不确定如何使用 AzureAD 组件及其所需的 authProvider 在手动登录和强制登录时触发此操作。

目前,我在 componentDidMount 函数中的索引组件中添加了一个调用来调用 API 以获取数据,但是如果用户不在索引页面上并刷新页面,则应用程序会中断,因为 API 调用不是AD登录完成后触发。

我不想在我的 auth reducer 中触发调用,我认为这对于 Redux 及其应该如何使用来说是一种反模式。

如何利用“AAD_LOGIN_SUCCESS”或“AAD_INITIALIZED”操作,以便在登录后始终触发我的 API 调用,从而避免在我的组件中添加逻辑?

这基本上是我目前所拥有的,它有效,但如果你在 /some-other-page 并点击刷新,则不会,因为这不会触发 API 调用。

应用程序.js

...
<Router>
    <Header />
    <AzureAD provider={ authProvider } reduxStore={ reduxStore } forceLogin={ true }>
        <Switch>
            <Route exact path="/">
                <EnvironmentsOverview />
            </Route>
            <Route path="/some-other-page">
                <SomeOtherPage />
            </Route>
            <Route path="*">
                <NotFound />
            </Route>
        </Switch>
    </AzureAD>
</Router>
...

EnvironmentsOverview.js

...
export class EnvironmentsOverview extends Component {
    componentDidMount() {
        this.props.getSystemsAndEnvironments();
    }

    render() {
        ...
    }
}
...

标签: reactjsreact-reduxmsalreact-aad-msal

解决方案


取决于你想如何处理这个问题,但对我来说,我很高兴使用 redux-saga,如果这是你的首选,你可以用 thunk 做一些类似的事情。

  1. 登录事件的简单观察者
  2. 工作人员触发您在登录后需要执行的任何副作用,即您需要进行的异步或阻塞请求/连接。
  3. 可能从您的工作函数中调度其他操作

注意:redux-saga 文档很棒,非常详细,但我刚刚为您的特定用例做了以下示例:

import { takeLatest, put, call } from 'redux-saga/effects';

//watcher 
function* watchForLoginSuccess() {
    yield takeLatest('AAD_LOGIN_SUCCESS', doPostLoginWorker); 
};

//worker
function* doPostLoginWorker() {
    try {
        //async action 
        const response = yield call(functionRefToFetchData, someParameterForFunction);
        //Dispatch another action with returned async data
        yield put(addUserData(response)); 
    } catch (error) {
        //dispatch an error action with the error info as payload
        yield put(addError(error));
    }
};

export default [
    watchForLoginSuccess
]


推荐阅读