[英]Correct way to write in dependency array when dispatch an action using hooks in redux
[英]Correct way to dispatch redux action from request
我正在使用redux-thunk,并且有以下操作:
export const fetchUserInfo = () => dispatch => {
return fetchCurrentUser()
.then(user => {
dispatch(retrieveUser(user));
if (user && user.settings && user.settings.storePageId) {
dispatch(getStoreById(user.settings.storePageId));
}
return user;
})
.catch(err => {
console.error('Fetching userinfo failed', err);
return Promise.reject(err);
});
};
fetchCurrentUser是一个api调用,定义如下:
export const fetchCurrentUser = () => authenticatedRequest('/customer');
这是我的authenticatedRequest:
import { logoutUser } from '../../actions/auth';
export const authenticatedRequest = (url, opts = {}, req = request) => {
if (!cachedTokenType || !cachedAccessToken) {
logoutUser() // I want this to happen!! :(
return Promise.reject(
new Error(
'Missing token_type & access_token needed to perform this request'
)
);
}
const headers = { ...defaultOpts.headers, ...(opts.headers || {}) };
const authedOpts = {
...opts,
headers: {
...headers,
Authorization: `${cachedTokenType} ${cachedAccessToken}`
}
};
return req(url, authedOpts);
};
我希望能够在我的authenticatedRequest函数中调度logoutUser(),因此我不必在所有使用authenticatedRequest的地方重复此逻辑。 我的问题是我不知道如何从另一个文件调用redux动作,以及何时不在带有connect的react组件中。
I want to be able to dispatch logoutUser() in my authenticatedRequest func...
我要说的是,通过实现这一点, authenticatedRequest
不仅可以完成一件事(对用户进行身份验证并可能注销用户)。 随着时间的流逝,如果您想将redux-thunk
更改为其他内容,复杂性可能会增加并且变得更糟。
如果仍然需要它,则可以传播dispatch
以便可以调度其他操作:
const fetchCurrentUser = (dispatch) => authenticatedRequest(dispatch, '/customer')
const authenticatedRequest = (dispatch, url, opts = {}, req = request) => {
if (YOUR_CONDITION) {
dispatch(logoutUser())
}
...
}
我个人不会这样做,因为它会将dispatch
公开给外部呼叫。 这是您的选择:)
是否可以在fetchUserInfo
操作中处理logoutUser
?
const authenticatedRequest = (url, opts = {}, req = request) => {
if (YOUR_CONDITION) {
return Promise.reject('LOGOUT')
}
...
}
const fetchUserInfo = () => dispatch => {
return fetchCurrentUser()
.then(user => {
...
})
.catch(err => {
if (err === 'LOGOUT') {
dispatch(logoutUser())
}
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.