reactjs - 使用 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() {
...
}
}
...
解决方案
取决于你想如何处理这个问题,但对我来说,我很高兴使用 redux-saga,如果这是你的首选,你可以用 thunk 做一些类似的事情。
- 登录事件的简单观察者
- 工作人员触发您在登录后需要执行的任何副作用,即您需要进行的异步或阻塞请求/连接。
- 可能从您的工作函数中调度其他操作
注意: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
]
推荐阅读
- c# - Asp Net web api 2 响应缓存(服务器端)
- unity3d - 为什么导航网格从不工作?单击烘焙后我看不到蓝色路径
- excel - 如何将格式化文本从 Word 传输到 Excel?
- javascript - 当我尝试使用谷歌助手时,将上下文从一个意图传递到另一个意图时获取“空”上下文
- angular - Angular 2+如何通过兄弟组件中的mouseleave事件触发切换指令
- python - 如何使用 Tkinter 创建 GUI?(苹果系统)
- git - 仅将分支中的最后一次提交合并到 master
- angular - Angular:为什么单击保存按钮时会自动导航
- android - 无法从 java 类调用 kotlin 片段
- python - 如何将输入文件作为参数在 Python 中读取?