我正在关注一篇博客文章,尝试在我的应用程序中实现用户登录
https://auth0.com/blog/secure-your-react-and-redux-app-with-jwt-authentication/
它建议在我的操作中执行以下操作
// actions.js
export const LOGIN_REQUEST = 'LOGIN_REQUEST'
function requestLogin(creds) {
return {
type: LOGIN_REQUEST,
isFetching: true,
isAuthenticated: false,
creds
}
}
// .....
export function loginUser(creds) {
let config = {
method: 'POST',
headers: { 'Content-Type':'application/x-www-form-urlencoded' },
body: `username=${creds.username}&password=${creds.password}`
}
console.log(creds) // <-- this works
return dispatch => {
console.log(creds) // <-- this doesnt work and everything after it doesnt work
// We dispatch requestLogin to kickoff the call to the API
dispatch(requestLogin(creds))
return fetch('http://localhost:3001/sessions/create', config)
.then(response =>
response.json().then(user => ({ user, response }))
).then(({ user, response }) => {
if (!response.ok) {
// If there was a problem, we want to
// dispatch the error condition
dispatch(loginError(user.message))
return Promise.reject(user)
} else {
// If login was successful, set the token in local storage
localStorage.setItem('id_token', user.id_token)
localStorage.setItem('id_token', user.access_token)
// Dispatch the success action
dispatch(receiveLogin(user))
}
}).catch(err => console.log("Error: ", err))
}
}
但是,一旦函数到达 returndispatch => {
部分,就会引发错误
--- 编辑 --- 下面的答案修复了控制台错误,但引入了新错误
最佳答案
您似乎没有设置 Redux Thunk,这是一个允许您进行异步操作的 Redux 库。
在本教程中,您linked ,解释了如何设置:
import thunkMiddleware from 'redux-thunk'
let createStoreWithMiddleware = applyMiddleware(thunkMiddleware, api)(createStore)
您应该阅读有关 Redux Thunk 的更多信息 here .
关于javascript - 尝试让操作和 reducer 工作时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44035108/