在此类项目中成功登录后如何将我的网站重定向到主页:
https://github.com/bradtraversy/mern_shopping_list
操作 ts 文件 [actions/authActions.ts]:
import axios from 'axios';
import { returnErrors } from './errorActions';
import {
USER_LOADED,
USER_LOADING,
AUTH_ERROR,
LOGIN_SUCCESS,
LOGIN_FAIL,
LOGOUT_SUCCESS,
REGISTER_SUCCESS,
REGISTER_FAIL
} from './types';
import { IAuthFunction, IConfigHeaders } from '../../types/interfaces';
import { useHistory } from 'react-router-dom';
//
// Register User
export const register = ({ name, email, password }: IAuthFunction) => (
dispatch: Function
) => {
// Headers
const config = {
headers: {
'Content-Type': 'application/json'
}
};
// Request body
const body = JSON.stringify({ name, email, password });
axios
.post('/api/auth/register', body, config)
.then(res =>
dispatch({
type: REGISTER_SUCCESS,
payload: res.data
})
)
.catch(err => {
dispatch(
returnErrors(err.response.data, err.response.status, 'REGISTER_FAIL')
);
dispatch({
type: REGISTER_FAIL
});
});
};
// Login User
export const login = ({ email, password }: IAuthFunction) => (
dispatch: Function
) => {
// Headers
const config = {
headers: {
'Content-Type': 'application/json'
}
};
// Request body
const body = JSON.stringify({ email, password });
const history = useHistory();// <---------- ERROR HERE
axios
.post('/api/auth/login', body, config)
.then(res => {
dispatch({
type: LOGIN_SUCCESS,
payload: res.data
});
// const history = useHistory(); <----- tried placing it here too
// history.push("/dd");
}
)
.catch(err => {
dispatch(
console.log(err)
// returnErrors(err.response.data, err.response.status, 'LOGIN_FAIL')
);
dispatch({
type: LOGIN_FAIL
});
});
};
catch 错误返回“错误:无效的钩子调用。钩子只能在函数组件的主体内部调用...”
POPMUISE
相关分类