我正在使用 Redux,并向 RESTful API 调度 Redux Thunk Fetch 调用以验证登录凭据。 API 成功在响应中返回 JWT(授权 token )。
我的Reducer配置为使用此 token 更新存储,但它返回“未定义”而不是 token 。我可以在 Redux Logger Action Payload 中看到 token - 所以我不确定发生了什么。
我怀疑这是因为 API 发送 token 的速度不够快,并且我的Reducer 正在使用未解析的值进行更新。日志确实表明了这一点,但我也很困惑为什么 - 当我在 console.log 中打开操作时,Promise 的状态在同一条目中从待处理到已完成波动!
我将发布我的 Action +Reducer 代码和相关的控制台日志 - 如果有人能指出我的错误的正确方向,我将非常感激:
/// REDUCERS
const initialState = { isAuthenticated: false}
const authReducer = (state = initialState, action) => {
switch(action.type){
case ('USER_AUTHENTICATED'): {
return Object.assign({}, state, {
isAuthenticated: true,
token: action.userInfo.token,
}
)
}
case ('INVALID_CREDENTIALS'): {
return Object.assign({}, state, {
isAuthenticated:false
}
)
}
default:
return state
}
/// ACTIONS
function authSuccess (userInfo) {
return {
type:'USER_AUTHENTICATED',
userInfo
}
}
function authFail () {
return {
type: 'INVALID_CREDENTIALS'
}
}
export function attemptLogIn(credentials) {
return dispatch => {
return fetch('http://localhost:3001/authorize', {
headers:{
'Content-Type': 'application/json'
},
method: 'POST',
mode: 'cors',
body: JSON.stringify(credentials)
})
.then(response => response.ok ? dispatch(authSuccess(response.json())) : dispatch(authFail()))
}
}
最初,Redux 日志将操作显示为待处理的 Promise:
但是,当我打开相同的操作时,我可以清楚地看到 Promise 的状态已更改为决议,并且 token 实际上就在那里。
我假设 authSuccess() 调度只会在收到 (response.ok) 后触发 - 那么 Promise 怎么可能仍然处于待处理状态?
感谢任何帮助!
最佳答案
原因是您正在调度 reponse.json()
,它本身将返回 promise
此外,您需要将 json
结果从 fetch
传递回 authSuccess
操作创建者
将代码更改为:
.then(response => response.ok ? response.json() : throw new Error(response.statusText))
.then(json => dispatch(authSuccess(json))
.catch(err => dispatch(authFail()))
关于javascript - 尽管收到有效的操作有效负载(异步身份验证调用),为什么我的 Redux 状态没有更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48198286/