我正在关注一篇博文,试图在我的应用中实现用户登录
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))
}
}
但是,只要函数命中部件return dispatch => {
,就会出现错误
---编辑--- 以下答案修复了控制台错误,但引入了新错误
答案 0 :(得分:1)
您似乎没有设置Redux Thunk,这是一个允许您进行异步操作的Redux库。
在教程linked中,解释了如何设置它:
import thunkMiddleware from 'redux-thunk'
let createStoreWithMiddleware = applyMiddleware(thunkMiddleware, api)(createStore)
您应该阅读有关Redux Thunk here的更多信息。
答案 1 :(得分:0)
你在这里要做的是利用thunk,这是一个返回另一个函数的函数。
在redux中,用于在创建操作期间引起副作用,例如异步调用作为操作的一部分,以及生成辅助操作,例如从此异步请求调度响应。
如果您查看博客文章package.json,他们依赖于redux-thunk中间件包(https://www.npmjs.com/package/redux-thunk),您也需要它,并将其附加到您的商店......
import { createStore, applyMiddleware} from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';
const store = createStore(
rootReducer,
applyMiddleware(thunk)
);