Reactjs React Redux最佳实践更改身份验证状态
也许这很简单,但我正在考虑当用户会话(在后端)过期时如何更新状态的最佳方法 用户故事-用户根据后端服务进行身份验证。会话令牌使用Reactjs React Redux最佳实践更改身份验证状态,reactjs,redux,react-redux,Reactjs,Redux,React Redux,也许这很简单,但我正在考虑当用户会话(在后端)过期时如何更新状态的最佳方法 用户故事-用户根据后端服务进行身份验证。会话令牌使用localStorage保存,并在每次需要经过身份验证的请求时加载—到目前为止一切正常。 然后(假设在1h后)令牌已过期。如何分派操作和更新状态 代码片段: export function getPersons() { return (dispatch) => { dispatch(fetchDataRequest());
localStorage
保存,并在每次需要经过身份验证的请求时加载—到目前为止一切正常。
然后(假设在1h后)令牌已过期。如何分派操作和更新状态
代码片段:
export function getPersons() {
return (dispatch) => {
dispatch(fetchDataRequest());
doFetch('persons', {}, true).then((payload) => {
dispatch(receiveData(payload.data));
}).catch((error) => {
if (error.response && error.response.status===401) {
dispatch(logoutUser());
} else {
dispatch(fetchDataError(error.message));
}
})
}
}
正如你所看到的,我在这里检查响应状态
if (error.response && error.response.status===401) {
dispatch(logoutUser());
}
我使用了一个顶级函数doFetch
,下面是代码
let API_URL = "http://example.com/api/";
export default function doFetch(endpoint, configuration, authenticated) {
let token = localStorage.getItem('token');
let config = {'Content-Type': 'application/json'};
if (authenticated) {
if (token) {
config.headers = { 'Authorization': `${token}` };
} else {
return Promise.reject("No token available");
}
}
Object.assign(config, configuration);
return fetch(API_URL + endpoint, config)
.then(checkStatus)
}
我想在顶级函数中调度logoutUser
操作,以避免代码中出现样板文件。有可能吗?
或者,无论我在哪里提出请求,我都必须返回并检查状态
谢谢各位。如果您想在
doFetch
中获得调度,您应该像dispatch(doFetch(…)
一样调度doFetch
。您的doFetch
将成为导出默认函数doFetch(…){return(dispatch)=>{/*doFetch code*/}}
谢谢您的回答。但是我现在如何处理。然后(…)
从getPersons
函数中,我得到了。then()
不是一个函数。我看到的最简单的方法是返回(分派)=>新承诺((解析)=>{/*doFetch code*/})
并在您的检查状态中激发解析()
谢谢,救了我的一天:)