我执行以下操作,使用redux-thunk登录用户。
export const loginUser = userData => dispatch => {
Axios.post('/users/login', userData)
.then( res => {
// retrieve token from the response
const token = res.data.token;
// console.log(token);
// pass the token in session
sessionStorage.setItem("jwtToken", token);
// set the auth token
setAuthToken(token);
// decode the auth token
const decoded = jwt_decode(token);
// pass the decoded token
dispatch(setCurrentUser(decoded))
})
.catch(err => {
if(err.response.data){
console.log(err.response)
dispatch({
type: GET_ERRORS,
payload: err.response.data
})
}
})
}
export const setCurrentUser = (decoded, dispatch) => {
return{
type:SET_CURRENT_USER,
payload:decoded,
}
}
我将如何将该动作转换为saga函数/动作?
当前后端抛出错误,
错误请求
可能是因为其未获取正确的数据或其他东西。
这是我的尝试
action.js
export const userLogin = userData => dispatch => ({
type: SET_CURRENT_USER,
userData
})
export const userLogInSuccess = data => ({
type: USER_LOG_IN_SUCCESS,
data
})
export const userLogInFailure = error => ({
type: USER_LOG_IN_FAILURE,
error
})
export const setCurrentUser = (decoded, dispatch) => {
return{
type:SET_CURRENT_USER,
payload:decoded,
}
}
saga / auth.js
import api from '../api';
import { SET_CURRENT_USER, GET_ERRORS, GET_CURRENT_USER} from '../actions/types';
import {userLogInSuccess, setCurrentUser, userLogInFailure} from '../actions/authActions';
export function* userLogin(action){
try{
const user = yield call(api.user.loginUser, action.data);
const token = user.token
console.log(token);
// pass the token in session
sessionStorage.setItem("jwtToken", token);
setAuthToken(token);
const decoded = jwt_decode(token);
// pass the decoded token
// dispatch(setCurrentUser(decoded))
yield put(userLogInSuccess(user));
yield put( setCurrentUser(decoded))
}
catch(error){
yield put(userLogInFailure(error.response.data));
}
}
export function* watchUserLogIn() {
yield takeLatest(SET_CURRENT_USER, userLogin);
}
export default function* () {
yield fork(watchUserLogIn);
}
api
import Axios from './Axios';
export default {
user:{
loginUser: userData =>
Axios.post('/users/login',userData).then(res => res.data.token)
}
};
登录组件
.....
handleSubmit = (e) => {
e.preventDefault();
const {formData} = this.state;
const {username, password} = formData;
const creds = {
username,
password
}
this.props.userLogin(creds);
// console.log(creds);
}
....
const mapStateToProps = (state) => ({
auth: state.auth
})
const mapDispatchToProps = (dispatch) => ({
userLogin: (userData) => dispatch(userLogin(userData)),
})
export default connect(mapStateToProps, mapDispatchToProps)(Login)
答案 0 :(得分:0)
在“网络”选项卡中检查您的有效负载,如果调用了请求,则意味着来自您的saga函数的操作已传递到api中。