【发布时间】:2019-09-09 20:04:18
【问题描述】:
我正在制作一个反应应用程序,实现身份验证以使用 API 调用从服务器获取提供凭据的令牌。我的方法是完美的吗?
我将 Django API 用于后端,将 reactJS 用于前端,还使用 thunk 作为带有 redux 的中间件。
authAction.js
import {AUTH_USER} from "./types";
export const authUser = (username, password) =>
{
return (dispatch) => {
const data = {
username: username,
password: password
}
return fetch("http://127.0.0.1:8000/api/v1/login/auth/", {
method: 'POST',
body: JSON.stringify(data),
headers: {'Content-Type': 'application/json'}
})
.then(results => results.json())
.then(results => {
dispatch({
type: AUTH_USER,
payload: results
})
}
)
}
}
authReducer.js
import {AUTH_USER} from "../actions/types";
const initialState = {
errors: [],
token : '',
}
export default function (state=initialState,action) {
switch (action.type) {
case AUTH_USER:
return {
...state,
token:action.payload.token,
errors:action.payload.errors,
}
default:
return state
}
}
登录功能
login(e){
e.preventDefault();
if(this.state.username && this.state.password){
console.log("Login");
this.props.authUser(this.state.username,this.state.password)
.then(res=>console.log(res)) // undefined
}
}
我想将结果打印在从 API 获取的控制台上,或者以更解释的方式,我想从调用者的动作调用中返回获取的结果。即token: any token
【问题讨论】:
-
您可以使用选择器(如paruchuri-p 的答案),也可以在
authUser操作函数中返回最后一个.then中的内容。现在它正确调度,但隐式返回undefined。 -
是的,只需在您的
dispatch({type: AUTH_USER, payload: results})通话后添加return results -
@Brandon 兄弟非常感谢我已经得到了我想要的东西,非常感谢你让我开心了兄弟!
标签: javascript reactjs redux react-redux redux-thunk