用户通过身份验证后,我需要调用 2 个函数(AsyncStorage.setItem
和setAPIAuthorization
(,然后调用 2 个 redux 操作(LOAD_USER
和SET_SESSION_USER
(。根据下面的尝试,我将如何实现这一目标?还是我也应该为这两个函数创建 redux 操作?
const loginUserEpic = (action$, state$) =>
action$.pipe(
ofType('LOGIN_USER'),
mergeMap(() =>
from(axios.post(`/auth`, {})).pipe(
mergeMap(response =>
of(
AsyncStorage.setItem('id_token', response.data.token),
setAPIAuthorization(response.data.token),
{
type: 'LOAD_USER'
},
{
type: 'SET_SESSION_USER',
user: response.data.user
}
)
),
catchError(error => console.log(error))
)
)
);
感谢下面的 Anas,这是我用来实现我想要的更新。到目前为止很成功。存储id_token
后,它会包含在任何后续 api 调用的标头中。出于这个原因,我需要确保在调用LOAD_USER
api 调用之前保存id_token
。
const loginUserEpic = (action$, state$) =>
action$.pipe(
ofType('LOGIN_USER'),
mergeMap(() =>
from(axios.post(`/auth`, {})).pipe(
mergeMap(response => {
return new Observable(observer => {
AsyncStorage.setItem('id_token', response.data.token);
setAPIAuthorization(response.data.token);
observer.next(
{
type: 'LOAD_USER'
},
{
type: 'SET_SESSION_USER',
user: response.data.user
}
);
});
}),
catchError(error => console.log(error))
)
)
);
设置会话存储是一个副作用。 所以最好在水龙头上完成,
您的长篇故事应仅将动作作为输出返回(动作输入、动作输出(。如果你这样做,redux 会抱怨你没有返回普通操作。
我仍然会为{ type: 'LOAD_USER' }
和{ type: 'SET_SESSION_USER'}
创建动作创建器,因为它更干净。
const loginUserEpic = (action$, state$) =>
action$.pipe(
ofType('LOGIN_USER'),
mergeMap(() =>
from(axios.post('/auth', {})).pipe(
tap((response) => {
AsyncStorage.setItem('id_token', response.data.token)
setAPIAuthorization(response.data.token)
}),
mergeMap(response =>
of(
{
type: 'LOAD_USER',
},
{
type: 'SET_SESSION_USER',
user: response.data.user,
}
)
),
catchError(error => console.log(error))
)
)
)
另一种简单的方法是使用switchMap
switchMap(() => [
{
type: 'LOAD_USER',
},
{
type: 'SET_SESSION_USER',
user: response.data.user,
}
])
只要它是一个数组,它就会自动将结果包装到可观察量中。因此,您不再需要of()
它。我在我的项目中经常使用它。