【发布时间】:2020-11-21 16:48:27
【问题描述】:
我正在尝试在我的应用上创建用户身份验证。我创建了一个 api,当应用程序发出请求时将调用它,因此它可以使用我在请求对象中传递的 id 获取用户的数据。
现在遇到的问题是,当调用该 api 时,由于用户尚未登录,因此令牌为空,并且操作 (userLoaded) 不会调度,而是我在 .catch 中捕获的 getError 和 AuthError应该派送。
我的 redux 控制台显示 userLoaded 已分派,但 getError 和 AuthError 未分派。
这是代码.....
The reducer
import {AUTH_ERROR, LOGIN_FAIL, LOGIN_SUCCESS, LOGOUT_SUCCESS, REGISTER_FAIL, REGISTER_SUCCESS, USER_LOADED, USER_LOADING} from '../action/types'
const initialState = {
token : localStorage.getItem('token'),
isAuthenticated : null,
isLoading : false,
user : null
}
export default function (state=initialState, action){
switch (action.type) {
case USER_LOADING:
return {
... state,
isLoading : true
}
case USER_LOADED:
return {
...state,
isAuthenticated :true,
isLoading : false,
user : action.payload
}
case LOGIN_SUCCESS:
case REGISTER_SUCCESS:
return {
...state,
...action.payload,
isAuthenticated : true,
isLoading : false
}
case AUTH_ERROR:
case LOGIN_FAIL:
case REGISTER_FAIL:
case LOGOUT_SUCCESS:
localStorage.removeItem('token')
return {
...state,
token : null,
isLoading : false,
isAuthenticated : false,
user : null
}
default:
return state
}
}
This is the action
import {AUTH_ERROR, LOGIN_FAIL, LOGIN_SUCCESS, LOGOUT_SUCCESS, REGISTER_FAIL, REGISTER_SUCCESS, USER_LOADED, USER_LOADING} from './types'
import {returnError} from './errorActions'
// So the first thing i have to do here is to check for a token and load it
export const userLoaded = () => (dispatch, getState) => {
dispatch({type: USER_LOADING})
// get the token from the current state
const token = getState().auth.token
// creating our header
const req = {
headers : {"Content-Type":"application/json"}
}
// check if there's a token and if we have it, then we add it to the headers
if(token){
req.headers['x-auth-token'] = token
}
fetch('http://127.0.0.1:8000/auth/user', req)
.then(res => res.json())
.then(data => dispatch({
type : USER_LOADED,
payload : data
}))
.catch(err => {
dispatch(returnError(err.response.data, err.response.status))
dispatch({type: AUTH_ERROR})
})
}
【问题讨论】:
标签: javascript reactjs redux